DEV Community

loading...

Discussion on: What does "if(variable++)" do in Javascript

Collapse
peerreynders profile image
peerreynders • Edited

I think the issue is that postfix increment is often taught and therefore used as a statement rather than an expression - therefore the fact that it returns a value and the question of which value it returns rarely comes up.

In fact in 1996 Scott Meyers in More Effective C++ noted:

Item 6: Distinguish between postfix and prefix forms of increment and decrement operators
...
If you’re the kind who worries about efficiency, you probably broke into a sweat when you first saw the postfix increment function. That function has to create a temporary object for its return value (see Item 19)

and in 2008 in JavaScript: The Good Parts Douglas Crockford observes:

In my own practice, I observed that when I used ++ and --, my code tended to be too tight, too tricky, too cryptic. So, as a matter of discipline, I don’t use them any more. I think that as a result, my coding style has become cleaner.

So it's kind of surprising that the canonical for loop is given as

let str = '';

for (let i = 0; i < 9; i++) {
  str = str + i;
}

console.log(str); // expected output: "012345678"
Enter fullscreen mode Exit fullscreen mode

Given that the old value returned isn't used it would make more sense to use the prefix increment:

let str = '';

for (let i = 0; i < 9; ++i) {
  str = str + i;
}

console.log(str); // expected output: "012345678"
Enter fullscreen mode Exit fullscreen mode

though I hope that JavaScript engines optimize the unused return value out in any case.

Douglas Crockford's JSLint bans increment operators outright:

Expected '+= 1' and instead saw '++'.
  for (i = 0; i < 9; i++) {
Enter fullscreen mode Exit fullscreen mode

favouring instead:

let str = '';

for (let i = 0; i < 9; i += 1) {
  str = str + i;
}

console.log(str); // expected output: "012345678"
Enter fullscreen mode Exit fullscreen mode

... so there is an ESLint and TSLint rule for that.