Loading...
0

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
0

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 overwrites

let count = 1;
let count = 2; // Error! Already declared

Simple rule:

  • Use const by default (for values that don't change)

  • Use let when you need to reassign

  • Never use var in 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.

Your Answer

You need to be logged in to answer.

Login Register
383
Views
1
Answers
0
Votes
Have a Question?

Get answers from the community

Ask Question
Asked By
Brandon Harris
160 reputation
Topic
Programming

Browse more questions in this topic