One of these practise is that we can use a variable before declaring it.Yes, you heard it right;
In other words; a variable can be used before it has been declared.
So below syntax of a program is correct;
x = 5; console.log('x is', x); // 'x is 5' var x ;
What does the hoisting means?
Go to your console and type
console.log( a); //ReferenceError: a is not defined
So you got a reference error, a is not defined, which seems to be correct. Since there is no variable a in your scope you got an error.
Now take Example 2 :
console.log(b) //undefined var b;
Now you can see , there is no reference error. Since variable has been declared and JS engine has moved it to top. So varibale has been declared but not given any value and by default if variable is not initiated in JS then it would be assigned
undefined, hence the output s undefined. According to JS the above code would be compiled as
var b; console.log(b);
so what does we said , the variable decalarion has been moved to top, irrespective of it’s position.
Now guess the output of example 3.
console.log(c); //undefined var c = 3;
You can see the output is
undefined again, because the variable declartion is only moved to top not the variable assignment. and by defualt the variable would be assigned with an undefined value.
Example 3 would be interpretted as in JS engine
var c; console.log(c) c = 3;
So you got the concept of the hoisting , please give your answer for the follwoing code before scroll.
console.log('First d is:' d); var d = 9; console.log('Second d is : ', d);
//First d is : undefined.
//Second d is : 9.