loading...
Cover image for Invoke your function even before declaring it: Hoisting in JavaScript

Invoke your function even before declaring it: Hoisting in JavaScript

baijanaththaru profile image baijanathTharu Updated on ・1 min read

Take a Look

Example:


add(2, 6); // 8

function add(x,y){
  return x+y;
}
  • We called the add function even before declaring it. This is possible in JavaScript because of Hoisting feature.
  • In hoisting, all the declarations are moved to the top of the current scope.
  • It is not only applicable to functions but to any other variables.
  • We can use any variable even before declaring it. For example:
num1 = 2;
console.log(num1); // 2
var num1;

Hoisting in Action

num1 = 2;
num2 = 6;
add(num1, num2); // 8
var num1;
var num2;
function add(x,y){
  return x+y;
}

let and const

num1 = 2;
console.log(num1); // ReferenceError: Cannot access 'num1' before initialization
let num1;
  • With let and const, we cannot use the variable before its declaration. If we try to use, we get RefrenceError as above.
  • This is because of hoisting in which the variables declared with let and const are moved to the top and are only declared but not initialized and hence ReferenceError.

Posted on by:

baijanaththaru profile

baijanathTharu

@baijanaththaru

I am aspiring web developer and tech blogger with a Bachelor's degree in Electronics and Communication Engineering.

Discussion

pic
Editor guide