Hoisting in JavaScript

Table of contents

No heading

No headings in the article.

Hoisting is a phenomenon in JavaScript that allows you to access variables and functions before they're even initialized. In other words, you can use a variable or a function before you declare it, and your program won't throw any errors.

To understand hoisting, let's first look at an example:

getJobAt() {
  console.log('Google');
}

var a = 'Learn daily';

console.log(a);
getJobAt();

In the above example, we declare a function getJobAt and initialize a variable before we use them. So the program will run without any issues, and it will print the following output:

Learn daily
Google

Now, let's make some changes to the program to see how hoisting works:

console.log(a); // Line 1
getJobAt();  // Line 2

getJobAt() {          // Line 3
  console.log('Google');
}

var a = 'Learn daily'; // Line 4

In this example, we're using the variable 'a' at line 1 and initializing it at line 4. Similarly, we're using the function getJobAt at line 2 and declare it at line 3. So what will be the output, and why?
The output will be:

undefined 
Google

If you guessed this output, then great! But if not, let's understand together.

First, let's understand what happens with the variable 'a'. When you run a JavaScript program, the execution context is created with two phases: memory creation and code execution. Before any line of code is executed, memory is assigned to functions and variables. For variables, the default value undefined is assigned to them. So, at the time of code execution, when we run console.log(a) on line 1, JavaScript doesn't see any value assigned to the variable yet, and it prints the default value undefined.

But what if we try to print a variable that hasn't even been declared? If we run console.log(z), JavaScript will give us a ReferenceError, because z has not been declared anywhere in the program. This is because, during the memory creation phase, JavaScript only assigns memory to variables that have been declared in the program.

Now, let's see what happens with the function. During the memory creation phase, when JavaScript encounters a function declaration, it copies the entire function and stores it in memory. This is different from what happens with variables, where the default value undefined is assigned. So when we try to run a function before or after its declaration, it doesn't matter, because JavaScript has already stored the entire function code in memory.
To see this in action, try running the following code:

console.log(getSomething); // line 1
function getSomething(){
  console.log('I have nothing')
}
console.log(getSomething); // line 3

This will print the following output:

function getSomething(){
  console.log('I have nothing')
}
function getSomething(){
  console.log('I have nothing')
}

So far, we've covered variables and normal functions, but what about arrow functions? Let's take a look at an example:

getArrow(); // Line 1, invoking the arrow function
var getArrow = () => {  // Line 2, declaring the arrow function
  console.log('I don\'t behave like a normal function :(');
}

In the above case, the program will throw the error called getArrow() is not a function. And that's because in the case of the arrow function at the time of memory creation, javascript does not copy the entire function code and store it in memory rather for the arrow function it behaves like variables and just assigns the value undefined.
Memory creation phase for Arrow function:

  {
    getArrow : undefined ; // real value will be assigned only at the time of code execution face 
  }

It is important to note that understanding the memory creation phase is key to understanding how hoisting works. With a solid understanding of memory creation, it becomes easier to understand the behaviour of hoisting with different types of functions and variables.

5 POINTS YOU SHOULD TAKE FROM THIS BLOG :

  1. Hoisting is a mechanism in JavaScript that allows variables and functions to be accessed before they are declared.

  2. During the memory creation phase of code execution, variables are assigned the default value of undefined, whereas functions are stored in memory in their entirety.

  3. When attempting to access a variable before it is declared, JavaScript will output the value undefined, while attempting to access an undeclared variable will result in a ReferenceError.

  4. Arrow functions are treated like variables during the memory creation phase, and so attempting to call an arrow function before it is declared will result in an error.

  5. To avoid confusion and unexpected behaviour, it's generally a good practice to declare all variables and functions at the beginning of the scope where they will be used, rather than relying on hoisting.

    That's all about Hoisting in Javascript. And thanks to Akshay Saini for creating an incredible Namaste Javascript playlist this blog is just whatever learning I had from there.