4 answers

★ Best answer

Guys are right that `var` is a problem, but the immutability thing with `const` isn't quite like that - `const` only freezes the reference, not the contents, so you can totally modify an object or array declared with `const`. What really makes the difference is scope: `var` is function-scoped (it leaks outside blocks), while `let` and `const` are block-scoped (they stay locked in the scope where they were created). This causes real bugs with `var`, like when you declare something inside an `if` and the variable shows up outside. My suggestion is to use `const` by default, `let` when you actually need to reassign, and forget about `var` altogether.

Don't use `var` in new code, seriously. It's the old way and it brings scoping issues that'll give you a headache later. The main difference is really in the scope: `var` has function scope, while `let` and `const` have block scope. That means if you declare a variable with `var` inside an `if`, it stays accessible outside the block. With `let` and `const` that doesn't happen, it stays stuck there.

Between `let` and `const`, the difference is simple: `let` you can reassign the value, `const` you can't. If you declare `const myVar = 5`, you can't do `myVar = 10` afterwards. With `let` it works fine. Seems like a small thing, but it's useful because it prevents you from changing a variable by accident. A lot of people prefer using `const` by default and only switch to `let` when they really need to reassign.

In practice, use `const` whenever you can, throw in `let` when you need to change the value, and forget about `var`. That's basically it. You'll still find tons of old code with `var`, but for new stuff it doesn't make sense 🤷

The scope difference that was mentioned is real, but what's actually practical day-to-day is immutability! With `const` you guarantee that the reference doesn't change, which prevents stupid bugs where someone (or you later on) accidentally reassigns a variable. `Let` is flexible when you need it, but `const` by default makes the code way more predictable and safe.

In practice, the hack nobody mentions is to use `const` by default and only switch to `let` when you actually need to reassign something - that way you force your brain to think more carefully about what's mutable and what isn't, and you avoid those annoying bugs where you change a variable without realizing it. `var` is pretty much obsolete anyway, people are right about that.

Your answer

Log into answer.