var x ; x = 50; console.log(x); // Output: 50
Another Example :
x = 50; console.log(x); var x ; // Output: 50
Why in both the case output is 50. For this, you will have to understand Hoisting.
According to MDN :
Don't worry I will explain in simple terms
Hoisting means MOVING the DECLARATION part of the variables at the top of the code.
Now you might be wondering 😒 . Am I mad or what for I have written 2 caps words that too between the sentence? But these two words hold great importance.
Hoisting is behind a scene process done by the JS engine. It is not like you will see your variables going all the way to the top of the code.
It is only about ** declaring** the variables, not about initializing them.
let x ; // Declaration var y ; // Declaration let x = 6 ; // Initialization var y = 5 ; // Initialization
Initialization of the variable will only take place once that code of line is executed.
Using "let" before it is declared will give you a reference error.
car = "Volvo" ; console.log(car); let car; // Output: Reference error.
- Using "const" before it is declared will give you a syntax error.
car = "Volvo" ; console.log(car); const car; // Output: Syntax error.
Only var variables will be initialized that too with "undefined" value and let and const will not be initialized at all until that line of code is executed.
Hoisting doesn't take place in Arrow function and class.
var x = 10; y = 10 ; console.log (x+y); var y ; // Output : ?
var x = 10; console.log(x + y); var y = 10; // Output: ?
x = 10; y=10; console.log(x + y); const x; let y; // Output: ?
NOTE: You might be getting a little overwhelmed but don't be as a developer you should have an understanding about hoisting. A simple way to tackle this issue is just declaring the variable at the top and you are good to go.
That's all for this blog. We will meet in the next blog until then Keep Learning, Keep Growing.
Do Answer these questions in the comment section.
You can connect with me 👇