Google JS Coding Conventions - "The var keyword must not be used"

200 Views Asked by At

I am having troubles understanding this paragraph:

Declare all local variables with either const or let. Use const by default, unless a variable needs to be reassigned. The var keyword must not be used

Could someone please explain what this means? Why shouldn't I use the 'var' keyword?

1

There are 1 best solutions below

13
On BEST ANSWER

Those conventions are assuming ES2015 and above, which have let and const, which can be used to replace var. They're saying don't use var anymore, because the let and const semantics are more useful (according to those conventions [and my own personal opinion, not that that matters]).

So for example, they're saying don't do this:

function foo() {
    for (var i = 0; i < 10; ++i) {
        // Do something with i
    }
}

instead, either do this:

function foo() {
    let i;
    for (i = 0; i < 10; ++i) {
        // Do something with i
    }
}

or this (but note that performance will be slightly slower with this last version, not that it usually matters1):

function foo() {
    for (let i = 0; i < 10; ++i) {
        // Do something with i
    }
}

Similarly, if you're using a variable whose value will never change, use const:

function getTomorrow() {
    const date = new Date();
    date.setDate(date.getDate() + 1);
    return date;
}

We can use const there because the value of date never changes (just the state of the object it refers to).

If you're anything like me, when you put these into practice (I don't follow those conventions, but I do follow this specific example of using let and const), if you're using other good practices (like keeping functions small, etc.), you'll be surprised at just how often you use const rather than let because you end up with a lot of "variables" whose values you never want to change.


1 You may be wondering why there's a performance difference between

function foo() {
    let i;
    for (i = 0; i < 10; ++i) {
        // Do something with i
    }
}

and

function foo() {
    for (let i = 0; i < 10; ++i) {
        // Do something with i
    }
}

The reason is that in the second one, a new i variable is created for every loop iteration. We can see that if we create a closure inside the loop:

function foo1() {
    console.log("let outside the loop:");
    let i;
    for (i = 0; i < 5; ++i) {
        setTimeout(() => {
            console.log(i);
        }, 0);
    }
}
function foo2() {
    console.log("let inside the loop:");
    for (let i = 0; i < 5; ++i) {
        setTimeout(() => {
            console.log(i);
        }, 0);
    }
}

foo1();
setTimeout(foo2, 50);
.as-console-wrapper {
  max-height: 100% !important;
}

Again, the performance difference almost never matters (and will get smaller as engines get better at optimizing it out when they can), and lots of times you want the behavior of the second form (which is why it's defined that way). But it's there.