26
JavaScript Hoisting
Hoisting is a default behaviour of JavaScript. It moves the declaration of variables and functions to the top of the current scope (script or function). In that way, a variable can be declared after it has been used and a function can be called before it is even written .
For example , the given code will not show any error ,by default var x will be moved before x = 20.
x = 20;
console.log(x);
var x;
Output: 20
But this will only work if we use the var keyword.
Example :
var x = 5;//Initialize x
console.log(`The values of x and y are: ${x} and ${y}`);
var y = 9;//Initialize y , won’t be hoisted
Output : The values of x and y are: 5 and undefined
The variables declared with let and const keyword are hoisted to the top but will not work because they are not initialized.
Reference Error occurs when a non-existent variable is referenced. The variable declared with 'let' keyword will be considered non-existent until it is declared.
Example :
y = 10;
console.log(y);
let y;
Output : ReferenceError: Cannot access 'y' before initialization
Using the 'const' keyword is considered as Syntax Error. So the code will not run.
Example :
y = 10;
console.log(y);
const y;
Output : SyntaxError: Missing initializer in const declaration
26