Why is var not deprecated?

Backwards compatibility.

You're right in saying there is no real advantage to using var over let - if you define them at the start of a function their meaning is basically identical.

You're right that there is no real reason to write new code using var (except maybe this, if relevant).

There are pages on the internet that are decades old though, and no one is going to rewrite them. There is nothing really to gain by removing var from the language. For languages like HTML and Javascript that are interpreted - backward compatability is absolutely mandatory.

That is also why they chose not to simply redefine var. Take the following example code;

// THIS IS AN EXAMPLE OF BAD CODE. DO NOT COPY AND PASTE THIS.
if (logic) {
    var output = "true"
} else {
    var output = "false"
}
console.log(output)

If var was changed to behave like let then the console.log would cause a reference error because of the scope difference.


I believe sometimes you need to redeclare a variable to write less code.

One example is this function that generates a unique id:

function makeUniqueId(takenIds) {
  do {
    var id = Number.parseInt(Math.random() * 10);
  } while (takenIds.includes(id))
}

Which may be invoked like that

makeUniqueId([1,2,3,4,5,6,7])

Here I declare id variable simply inside do block and it get's "hoisted" to the function scope. That would cause an error if I used let, because while block wouldn't see the variable from the do block. Of course I could declate let before do..while, but that would create the same function scoped variable with extra line of code.

Another example is when you copypaste code to devtools console and every time variables get redeclared.

One more example. What if you want to keep your variable declarations close to their usages but still treat them as function globals? If you use let in this fashion, you'll get rather confusing expirience in dev tools (all those Block, Block scopes). enter image description here

But var 'keeps' them together in one 'Local' list: enter image description here