Difference Between let and var in JavaScript Explained
In JavaScript, both let and var are used to declare variables — but they behave very differently. Understanding the difference between them is essential for writing cleaner, bug-free code. This guide explains the key differences between let and var in terms of scope, hoisting, global behavior, and redeclaration, along with examples showing when you should use let instead of var.
Difference Between let and var in JavaScript Explained
coldshadow44 on 2025-10-14
Make a comment
_
2025-10-14
The biggest difference between let and var lies in variable scope.
Example:
Here, moo (declared with var) is accessible outside its block, while baz (declared with let) is not.
2. Hoisting Behavior
Both var and let are hoisted, but they behave differently:
Example with var:
Example with let:
3. Global Object Property
At the global level, variables declared with var become properties of the global object (window in browsers), while variables declared with let do not.
This makes let safer to use in modern JavaScript because it avoids accidental overwriting of global variables.
4. Redeclaration
Redeclaring a var variable in the same scope is allowed, but redeclaring a let variable causes a SyntaxError.
5. When to Use let Instead of var
You should always prefer let (or const) over var in modern JavaScript because:
Example of a common bug fixed by using let:
If you used var, all logs would show 3 because var doesn’t create a new scope per loop iteration.
Conclusion
Use let whenever you need a variable that can be reassigned but should stay within its block. Avoid var in modern code unless you are maintaining older JavaScript that depends on it. The introduction of let in ES6 made variable handling more predictable and safer for developers.