javascriptecmascript-6deprecatedvarlet

Why is var not deprecated?


Lately after ES6 released, many sources suggested that I use "const" and "let" instead of "var", and that I should stop using "var" in my JavaScript.

What I wonder is, if "var" has no advantage over "let" in all points of view, then why didn't they just fix var, or even deprecate "var" instead of letting them go along side each other?


Solution

  • 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.