Why does everyone say you should never use var in JavaScript anymore?
I learned JavaScript from an older course and they used var everywhere. Now I see people online saying var is basically evil and you should only use let and const. But my code works fine with var? Can someone explain what the actual problem is in simple terms?
1 Answer
Best -->
Great question - this confused me too when I was learning. Let me explain with actual examples:
The main problems with var:
1. Function scope vs block scope
// With var - this works (but shouldn't!)
if (true) {
var name = "John";
}
console.log(name); // "John" - var ignores the block// With let - this fails (correctly!)
if (true) {
let name = "John";
}
console.log(name); // Error - name is not defined
2. Hoisting weirdness
console.log(x); // undefined (not an error!)
var x = 5;console.log(y); // Error - cannot access before initialization
let y = 5;
With var, the declaration gets hoisted but not the value. This causes confusing bugs.
3. No protection from accidental redeclaration
var count = 1;
var count = 2; // No error, silently overwriteslet count = 1;
let count = 2; // Error! Already declared
Simple rule:
- Use
constby default (for values that don't change) - Use
letwhen you need to reassign - Never use
varin new code
Your old code works because JavaScript is backwards compatible. But you're setting yourself up for subtle bugs that are hard to track down. Just get in the habit of using const/let.
Asked By
Topic
Browse more questions in this topic
Hot Questions
-
How do I validate a startup idea before quitting m...
908 views -
Why is my WiFi so slow even though I have fast int...
904 views -
Is Duolingo actually effective for learning a lang...
900 views -
Side hustle vs full business - when do you make th...
796 views -
Are online degrees taken seriously by employers?
790 views
Top Users
-
1
1,000
-
2
320
-
3
282
-
4
270
-
5
255
Recent Blogs
View AllRecent Activity
-
Stephanie White answered
What is the hardest language for English... -
Brittany Thomas asked
Remote team management - how do you know... -
Christopher Miller answered
Which Linux distribution would you recom... -
Ashley Davis answered
Best way to track monthly expenses witho... -
David Jones asked
What's the best programming language to ...