DEV Community

Cover image for JavaScript Hoisting for beginners
Yash K
Yash K

Posted on • Edited on

JavaScript Hoisting for beginners

Hoisting might be difficult for you to understand as a JavaScript beginner. Let me simplify that for you!

In simple words, Hoisting is the default behavior of JavaScript of moving variables declarations at the top of script or function.

Note: JavaScript only hoists the variable declarations at the top, not the initialized variables. It will be clear once we go through examples.

Important: JavaScript hoisting only works with variables declared with var keyword not let/const keywords.

Let's make it clear by examples.

1) Hoisting of variable declarations:

Example 1

Output:
Output 1

Look at the above example, the output produced because JavaScript hoists the variable declaration at line 16 to the top of the script. So if you try by putting that declaration of line 16 to line 11, it will produce the same output.

2) Hoisting of variable initializations:

Example 2

Output:
Output 2

As stated in the above note, JavaScript will not hoist variable initializations. So in the output, it gives undefined at line 12 because at line 14 I have initialized variable x with value 5 not just declared.

you might have a question that why x is undefined instead of giving me an error. look at the below snippet.

Alt Text

Behind the scene, JavaScript will make the code like the above snippet by hoisting declaration of variable x. That's why it will give the value of x undefined instead of an error.

Now I hope, that note makes sense that JavaScript only hoists declarations not the initializations of variables.

Hoisting is the default behavior that might cause unexpected results. And it would be very hard to find this kind of problem. So to avoid this follow below rules:

  • Always use new ways of declaring and initializing variables using let/const keywords.
  • Always declare variables at the top of scope (Global or Function or block Scopes).
  • If you really want to use var keyword enable strict mode in the script. You can refer to this article about strict mode in JavaScript: https://www.w3schools.com/js/js_strict.asp

Here Ends, I hope Hoisting makes sense to you. Also, comment down below your thoughts on it.

Good Luck!

Top comments (0)