What is hoisting of variables and functions in JavaScript?
What is hoisting of variables and functions in JavaScript?
Web Developer
I am a professional .NET developer with over 4 years of hands-on industry experience in designing, developing, and maintaining scalable web applications. I specialize in .NET Core, C#, RESTful APIs, and database-driven systems using SQL Server.
In layman's terms, hoisting in JavaScript is as if the browser wanted to give you a note saying “Let me first go and put all your variable and function declarations to the top of your code before we proceed to run it.”
Here's what it means:
1. Variables: If you declare a variable with var then it will be moved to the top level of its scope. As we saw, only a declaration is hoisted, not the variable's value or initialization.
For example:
2. Functions: When defining a function using the function keyword the whole function name and the codes that make up the function are also hoisted.
For example:
3. Let and Const: The variables defined by let and const are also hoisted but they cannot be used before declaration in the code. This is known as the temporal dead zone:
Hoisting in JavaScript can be described as ‘moving’ declarations to the top of the scope alongside omitting the movement of values or initializations. That is why it is recommended to declare variables as well as functions beforehand to avoid confusion and deliver better code!
Explore the reasons behind JavaScript's enduring popularity as the go-to programming language in this article