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:
console.log(a); // undefined (because only the declaration is hoisted, not the value)
var a = 10;
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:
sayHello(); // Works fine because the function is hoisted
function sayHello() {
console.log("Hello!");
}
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:
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 20;
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
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
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