This content originally appeared on DEV Community and was authored by Crosston J
Opening Lines:
Today, let’s talk about Hoisting and Non-Hoisting, which are two of the most confusing but important things in JavaScript. If you know how variables and functions work before you declare them, you won’t run into any tricky bugs and your JS skills will get better.
What is Hoisting?
Hoisting is JavaScript’s default behavior of moving variable and function declarations to the top of their scope before code execution.
What Gets Hoisted ?
-/ Function Declarations = Fully hoisted
-/ Variable declared with var = its hoisted but its return undefined
-/ Variable declared Let & Const = Hoisted but not initialized , they remain into TDZ . until they’re defined
Lets View some example:
1. Function Hoisting
display();
function display() {
console.log("Hello, Alice!");
}
Output:
Hello, Alice!
Here the function is hoisted , the function call is in top . In js its execute line by line when its reach the “display()”. Then its check the entire code . where is the ” display()”. This how its works.
2. Variable Hoisting with var
console.log(a);
var a = 10;
Output: undefined
Because var a is hoisted, but its value (10) isn’t assigned until later. Therefore “a” always returns undefined . Note this question maybe its your future interview question.
3. Variable Hoisting with let & const
console.log(b);
let b = 20;
Error: ReferenceError: Cannot access 'b' before initialization
Why? Because let and const are hoisted but not initialized. They live in the Temporal Dead Zone (TDZ) until declared.
What is Non-Hoisting ?
Its refer to anything thing can’t be used before it’s declared.
eg:
When used early, let and const variables act like they aren’t hoisted because they throw an error.
Function expressions and arrow functions that are assigned to variables do not hoist like regular functions do.
Example:
add(2, 3);
const add = (x, y) => x + y;
Error: Cannot access 'add' before initialization
Pro Tips From ChatGPT :
-/ Always declare your variables and functions at the top of their scope to avoid confusion.
-/ Prefer let and const for block-scoping and safer code.
-/ Understand TDZ when using let and const.
*Conclusion: *
Hoisting can make JavaScript seem random, but once you learn how it works, you’ll be able to write code that is cleaner and more reliable. Always make it clear what your variables and functions are and how to use them. Don’t rely on hoisting to “save” you.
Quotes Time:
“Learning is not about knowing everything, but about asking better questions.”
This content originally appeared on DEV Community and was authored by Crosston J