DEV Community

Cover image for Hoisting in JavaScript(Variables & function)
Srishti Prasad
Srishti Prasad

Posted on • Updated on

Hoisting in JavaScript(Variables & function)

Hoisting

What is Hoisting in JavaScript?

When the JavaScript engine executes the JavaScript code, it creates the global execution context. The global execution context has two phases: creation and execution. So, we can say even before code starts executing memory is allocated to each and every variable and function.

Variable hoisting

Variable hoisting means the JavaScript engine moves the variable declarations to the top of the script.

console.log(count);
var count=2;

Enter fullscreen mode Exit fullscreen mode

Image description

However, the first line of code doesn’t cause an error. The reason is that the JavaScript engine moves the variable declaration to the top of the script.

This code is similar to :-

var count;
console.log(count);
count=2;

Enter fullscreen mode Exit fullscreen mode

During the creation phase of the global execution context, the JavaScript engine places the variable counter in the memory and initialises its value to undefined.

screenShot144

But, if :-

var count=2;
console.log(count);
Enter fullscreen mode Exit fullscreen mode

This won't give any error.
screenShot142

The let keyword

console.log(count);
let count=2;
Enter fullscreen mode Exit fullscreen mode

ERROR MESSAGE: "ReferenceError: Cannot access 'counter' before initialization.

The error message explains that the count variable is already in the heap memory. However, it hasn’t been initialized.
Behind the scenes, the JavaScript engine hoists the variable declarations that use the let keyword. However, it doesn’t initialize the let variables.
NOTICE: if we have used var instead of let then it would give us “undefined”.
This shows that using the let keyword it assigns memory in the heap.

ScreenShot145

Function Hoisting

Like variables, the JavaScript engine also hoists the function declarations. This means that the JavaScript engine also moves the function declarations to the top of the script.

let alpha= 1,beta = 10;

let result = add(alpha, beta);
console.log(result);

function add(alpha, beta) {
  return alpha + beta;
}

Enter fullscreen mode Exit fullscreen mode

Here, function is called before defining it.
Still the output is correct, that is 11.

ss146
The result is same ,if

function add(alpha, beta) {
    return alpha + beta;
  }

let alpha= 1,beta = 10;

let result = add(alpha, beta);
console.log(result);

Enter fullscreen mode Exit fullscreen mode

lets see what happen if we use function expression :-

let alpha= 1,beta = 10;

let result = add(alpha, beta);
console.log(result);

var add=function(alpha, beta) {
  return alpha + beta;
}
Enter fullscreen mode Exit fullscreen mode

ERROR: Uncaught TypeError: add is not a function

ss147
Similar is the case with arrow function.

let alpha= 1,beta = 10;

let result = add(alpha, beta);
console.log(result);

var add=(alpha, beta) =>{
  return alpha+beta;
}

Enter fullscreen mode Exit fullscreen mode

ERROR: Uncaught TypeError: add is not a function.

This is because for function expression, we are storing function inside a variable, and when memory is allocated to variables it store undefined, so when we try to invoke the variable as a function, js finds undefined instead of a function, so it shows error that add() is not a function as that is actually a normal variable that you're are trying to access as a function.

KEY POINTS TO BE NOTED :-

  • JavaScript hoisting occurs during the creation phase of the execution context that moves the variable and function declarations to the top of the script.

  • The JavaScript engine hoists the variables declared using the let keyword, but it doesn’t initialize them as the variables declared with the var keyword.

  • The JavaScript engine doesn’t hoist the function expressions and arrow functions.

If you have any questions, leave a comment and I'll do my best to respond.
Give this article a like if you found it helpful and follow me for more articles like this.

Discussion (4)

Collapse
unthrottled profile image
Alex Simons

Hey alright, variables in functions also get hoisted.

function dostThouEvenHoist() {
  console.log(`Hello hoist: ${toHoist}`);
  var toHoist = {
    "I am": "created in function definition",
  };
  return toHoist;
}
Enter fullscreen mode Exit fullscreen mode

What happens when the same variable is defined in different scopes in the same function and they both get hoisted?

function howDoIHoist(hoistOrNotToHoist) {
  console.log(`What happens here? ${whatHappensWhenIGetHoisted}`);
  if(hoistOrNotToHoist) {
    var whatHappensWhenIGetHoisted = {
      "I probably get hoisted": "Hoist Away!"
    };
    console.log(`Yes Hoist Please! ${JSON.stringify(whatHappensWhenIGetHoisted, null, 2)}`)
  } else {
    var whatHappensWhenIGetHoisted = {
      "Most likely Hoisted": "Don't hoist."
    };
    console.log(`Don't Hoist Please! ${JSON.stringify(whatHappensWhenIGetHoisted, null, 2)}`)
  }
}

howDoIHoist(true);
howDoIHoist(false);
Enter fullscreen mode Exit fullscreen mode

Thanks for the post!

Collapse
srishtikprasad profile image
Srishti Prasad Author • Edited on

1st function call “howDoIHoist(true)” will print :-
What happens here? Undefined
And prints condition in “if” statement

This is because inside the scope of function “howDoIHoist()”,

“whatHappensWhenIGetHoisted” is variable and is used before it is defined. Hence,it will give “undefined”. According to the hoisting of variables which I’ve covered in this blog.

Image description

Moreover,“scope of a function” means the scope defined by the function's body, in which its local variables are declared

Variable “whatHappensWhenIGetHoisted” is inside a function so it is in the scope of that function. We can’t say here that variable “whatHappensWhenIGetHoisted” is in different scope if it used in if-else expression.

You can read more about Closure in my blog Link,here,I have covered this topic,it might be helpful for you!

Collapse
andrewbaisden profile image
Andrew Baisden

Great article!

Collapse
srishtikprasad profile image
Srishti Prasad Author

Glad you liked it!