DEV Community

SYED MAZHAR ALI RAZA
SYED MAZHAR ALI RAZA

Posted on

Hoisting in JavaScript [must know concept]

Did you know that JavaScript allocates memory to all variables and functions first, even before executing the code?

Yes, that's true. And this results in a phenomenon called "hoisting" in JavaScript.

Hoisting allows us to use variables and functions even before they're declared. Look at this example

console.log(x);
var x = 'sample';
Enter fullscreen mode Exit fullscreen mode

Interestingly, this will not throw an error. Instead, it will output undefined. Let's take a slightly deeper dive into this process.

  1. Variable hoisting

    • The interpreter hoists variables declared with var with a default value of "undefined". Therefore, If you use a variable declared with var before it's been declared, it will return undefined.
    • The interpreter also hoists variables declared with let or const, but this time, the variables are not assigned a default value. JS just knows that these variables exist in the code. Therefore, If you use a variable declared with let/const before it's been initialized, it will throw an error stating "cannot access xyz before initialization".
    • If you don't initialize the variable anywhere in the code, and try to use such variable, it will throw an error stating "xyz is not initialized". See how this time JS doesn't even know that xyz exists.
  2. Function hoisting

    • Unlike variables, an actual copy of the function is hoisted at the time of memory allocation. This gives an advantage of using calling functions even before they've been initialized.
    • Note that if you assign a function to a variable (like in arrow functions), it will no more be treated as a function. Just how variables are hoisted by a default value of undefined, this function will also be treated the same.

Want to read a detailed explanation with more examples, check out this amazing article by Zach Snoek on FreeCodeCamp's website.

Happy coding :)

10daysofJSfundamentals (DAY 7)

Top comments (0)