Hoisting in JavaScript
Before going into Hoisting let us see in how many ways we can declare a function in JavaScript.
1. Function Declaration :
We will write a simple function which adds two numbers and logs the sum in console.
function sum(a, b){
console.log(a+ b)
};
2. Function Expression :
const sum=function(a, b){
console.log(a+ b)
};
3. Arrow Function :
const sum=(a, b)=>{console.log(a+ b)};
Hoisting is a mechanism in JavaScript in which the function declarations are moved to the top of their scope before code execution
let x = 15;
let y = 10;
let result = add(x, y);
console.log(result); // 25
function add(a, b) {
return a + b
};
When we try to implement the same function using function expression we will get a Reference Error as Function expressions are not Hoisted. Check the below code:
let x = 15;
let y = 10;
let result = add(x, y);
console.log(result); // **Reference Error** { Cannot access 'add' before initialization }
const add=function(a, b) {
return a + b
};
Similarly Arrow functions are also not hoisted in JavaScript, We will get a below error:
let x = 15;
let y = 10;
let result = add(x, y);
console.log(result); // **Reference Error** { Cannot access 'add' before initialization }
const add=(a, b)=> {
return a + b;
};
When you have reached till here, I hope you've gone through the blog and this is my first blog which I wanted write for a longtime. Before writing this I thought Someone might have already written on this topic but felt let me write it for myself as notes. I tried to put what I have understood on this particular concept , If you find any errors/missing out do let me know I would love to learn.