Hoisting In JavaScript
Salman Abdullah Fahim
Software Engineer @Meeramind | Next.js | Typescript | Express.js | MongoDB | PostgreSQL | Actively Looking for Full Stack Web Developer Role
→ Let's observe the below code and its explanation -
getName(); // Hello Javascript!
console.log(x); // undefined
var x = 7;
function getName() {
console.log("Hello Javascript!");
? It should have been an outright error in many other languages, as
It is not possible to access something which is not even
created (defined) yet but in Javascript, We know that in the memory creation
phase it assigns undefined to variables and puts the content of the function to
the function's memory.
? And in execution, it then executes whatever is asked. Here, as
execution goes line by line and not after compiling, it could only
print undefined and nothing else. This phenomenon is not an
error. However, if we remove var x = 7; then it gives an error.
Uncaught Reference Error: x is not defined.
领英推荐
getName(); // Hello Javascript!
console.log(x); // Uncaught Reference: x is not defined.
console.log(getName); // f getName(){ console.log("Hello Javascript!); }
function getName(){
console.log("Hello Javascript!");
}
Hoisting is a concept which enables us to extract values of variables and functions even before initializing/assigning value without getting error and this is happening due to the 1st phase (memory creation phase) of the Execution Context.
→ So, in the previous article, we learned that execution context gets created
in two phases. Even before code execution, memory is created. So in
case of variable, it will be initialized as undefined while in the case of
function the whole function code is placed in the memory.
Now let's observe a different example and try to understand the output -
getName(); // Uncaught TypeError: getName is not a
function
console.log(getName);
var getName = function () {
console.log("Hello Javascript!");
}
// The code won't execute as the first line itself throws an error
Now let’s try to declare function using arrow operator -
getName(); // Uncaught TypeError: getName is not a function
console.log(getName);
var getName = () => {
console.log("Hello Javascript!");
}
// The code won't execute as the first line itself throws an
TypeError
In these two scenario, what happens? Here we declare the function inside a variable. We know in the memory creation phase memory will be allocated to the variable with a special keyword undefined and for function the whole code will be copied and stored in the memory. From the above two pieces of code, we see that we call the variable here, not the function and that's why it throws an error. So, function expression and arrow function are not hoisted here. These are the exceptions in hoisting.