Hoisting is a concept that enables us to extract values of variables and functions even before initialising/assigning value without getting errors. This happens due to the 1st (memory creation phase) of the Execution Context
.
Let's observe the below code and its explanation:
getName(); // Namaste Javascript
console.log(x); // undefined
var x = 7;
function getName() {
console.log("Namaste Javascript");
}
Namaste Javascript
undefined
- In many other programming languages, accessing something that hasn't been created (defined) would result in an outright error.
- However, in JavaScript, during the memory creation phase, it assigns 'undefined' to variables and allocates memory for functions.
- During execution, JavaScript executes whatever is asked of it.
- In JavaScript, execution happens line by line without prior compilation.
- Because of this, if a variable is accessed before it's declared and initialized, it will print 'undefined' without throwing an error.
- This behavior is not considered an error in JavaScript.
- However, if a variable is removed or accessed before it's declared and not initialized, it will result in an error like
Uncaught ReferenceError: x is not defined
.
So in Episode 2, we learned that execution context gets created in two phases, so even before code execution, memory is created so in the case of a variable, it will be initialized as undefined while in the case of function the whole function code is placed in the memory.
Note: Not defined & undefined are not the same.
getName(); // Namaste Javascript
console.log(x); // undefined
function getName() {
console.log("Namaste Javascript");
}
Uncaught ReferenceError: x is not defined at <anonymous>:2:17
- In the Arrow function, it's considered a variable instead of a function.
getName(); // Namaste Javascript
console.log(x); // undefined
var getName = () => {
console.log("Namaste Javascript");
}
Uncaught TypeError: getName is not a function at <anonymous>:2:5