Hoisting in JavaScript

What is Hoisting in JavaScript?

The dictionary meaning of hoisting is – raise (something) by means of ropes and pulleys.

That is what JavaScript means by hoisting. It pulls all the variable and function declarations on top of your code. Well, not literally. It moves the declarations to top during code compilation so the decelerations are available before initialising the variable or invoking function.

Let’s try to understand this with some examples:

Using variable before declaring

Invoking function before defining

Though, We should keep in mind that hoisting pulls only the declarations to top and not initialisations. So, the below example will always log `undefined`.

Best Practices

Though you get hoisting for free but the best practice says that we should always declare our variables and define our functions before using them and invoking them respectively in order to save ourselves some mess. Also, declarations first approach will make life easier during debugging.

Advertisements

One thought on “Hoisting in JavaScript”

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.