Launching Drycomponents - Get Free HTML/React Components built using TailwindCSS

Hoisting in Javascript

Following the series of my previous articles on Javascript, in the article I would like to explain you about a typical topic called Hoisting in Javascript

hoisting.png

The above statement might seem a bit complicated, let's see with an example. In any programming language we follow a simple pattern called declaration and initialization/assignment of a variable.

So, until the variable is assigned, the value of the variable will always be undefined.

Now can you predict the output of the following code?

Had you thought the output of the above code is "Saravanan Sampathkumar", then you're wrong. If you thought it's "Saravanan", then yet again you're wrong. The above code neither throws any error, nor a warning. The output of the above code is actually undefined.

Whenever you define any function with a variable in it, javascript interpreter pushes the variable declaration to the top of the code like the following

Hence, we see the output as undefined. Had we not assigned the variable name inside the function, then we would have got the output as "Saravanan Sampathkumar"

That's all there is to it. As mentioned earlier, Hoisting is nothing but moving the declaration of variable and function to top of your code block before execution. Hope you got the hang of it. See you in another article.

Happy Coding!

Would like to hear more from me?

Consider Signing up. No spam ever.

Name

Email

Topic