Dev

By Carlos Santana on
Reading time: 3 minutes

JavaScript-kPdZo.jpg

Hoisting can be confusing for many JavaScript developers, some of them does not understand how it works even having years of experience in this programming language, I'll try to explain you in a very easy way how the hoisting works in JavaScript.

When we write a function in JavaScript and we define a variable inside, the JavaScript interpreter hoist this variable, meaning that is going to be moved to the parent context. An analogy could be for example when we put water to boil and the bubbles (variables) goes up because they are the smallest particles and the rest of the elements (heavier particles) remain where they are.

Take a look at this code: 

var result = 0;

function sum(n1, n2) {
  alert(result);
      
  result = n1 + n2;
}

sum(1, 2);

alert(result);

If you execute this script, you will see two alerts, the first one will show 0 and the second one will be 3. But now take a look on this code and you will notice that variable (result) is defined now inside the function as a local variable.

var result = 0;

function sum(n1, n2) {
  alert(result);    

  var result = n1 + n2;
}

sum(1, 2);

alert(result);

Now if you run this code, you will see the first alert as undefined and the second one as 0, interesting, right?

This is what is happening: As I mentioned before, always that we define or we use a variable inside a function in JavaScript, this will hoist the variable to the top of the parent context, meaning that internally JavaScript reads the code like this: 

var result;
result = 0;

function sum(n1, n2) {
  var result; // This is the reason of the undefined value
  alert(result); 

  result = n1 + n2;
}

sum(1, 2);

alert(result); // This is the global result 0

This code makes more sense, right? As you can see the result variable is hoisted to the top context of the function, then will fire the alert which will display the undefined value and after will assign the value to result. And the last alert will return the value of the global result variable which is 0.

The first code was returning 0 and 3 because we did not define the variable result inside the function, that means JavaScript will read the code like this: 

Only members can see all the codes
You can Login or Sign Up

If you liked this post you can help us share it with your friends.

avatarLeave a comment

Your comment

Only members can comment. You can Login or Sign Up