What is hoisting in JavaScript?
- In Javascript, Hoisting is a concept in which Javascript brings all the variables declarations to the top of the script during execution.
- This means that if a variable is initialized at some part of the script while being accessed before its definition is valid and doesn't throw an error.
- But the assignment of variables happen at their original places which means that although variables are available before their actual place of declaration, their value is undefined.
console.log(`The value of x before is ${x}`);
var x = 10;
console.log(`The value of x after is ${x}`);
output:
The value of x before is undefined
The value of x after is 10
- variables declared using var keyword in the global execution context are "hoisted", which is why the above code works without issue.
- let keyword on the other hand by its design doesn't allow this to happen
console.log(`The value of x before is ${x}`);
let x = 10;
console.log(`The value of x after is ${x}`);
output:
console.log(`The value of x before is ${x}`);
^
ReferenceError: Cannot access 'x' before initialization