Understanding Hoisting.

Hey People, Hope you all are doing awesome. It’s been so long I have not written any post. A lot has happened. I graduated two months back(June).  Got a chance to visit San Francisco, USA. It’s was my first trip aboard, gain lot of new experience, met new people and some awesome developers. Have to say a lot of things about my USA visit and of-cause about Mozilla all hands. I will make sure to write a separate blog post for that.

Also my team got accepted as RGSoC fellow intern. We are working on Servo Project will write about it soon. Keep eye on my site there are lot to come.

Recently I was working on a project and I got confused about a term in JavaScript that is *Hoisting*.  Though it is pretty simple nothing to confuse about. So, I thought to share a very simple way to understand Hoisting.

Let me start by writing a function:

function calculateMyAge(year) {
console.log(2016 - year);
}
calculateMyAge(1996)

Output: 20

I am sure this is understandable and too straight forward.

So Hoisting is nothing but a JavaScript’s default behavior of moving declarations to the top like this:

calculateMyAge(1996)
function calculateMyAge(year) {
console.log(2016 - year);
}

and this will work.

Output: 20

So here in the creation face of the execution context which is a global execution context in this case. The function declaration called at this edge is stored in a variable object(even before the code is executed) this is how Hoisting works. Isn’t it is pretty simple?

Let me know if you have any question 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s