DEV Community

loading...
Cover image for What does "if(variable++)" do in Javascript

What does "if(variable++)" do in Javascript

π‹π„π‘½πˆπ‘¨π“π‡π€π Programming
I am a fifteen-year-old christian Homeschooler that is crazy about coding. I've been coding for about four years now. I also use HTML, CSS, JS, Flask (Python), PHP, SQL, React, P5js, and more!
・1 min read

I've noticed that if you do something in JS like below, no error will be thrown.

let num = 0;
if(num++){
  console.log("Number");
}
Enter fullscreen mode Exit fullscreen mode

I also noticed that if you do --, there is still no error thrown.

let num = 0;
if(num--){
  console.log("Number");
}
Enter fullscreen mode Exit fullscreen mode

Can someone explain to me what this does, what it's for, and why it happens?

Thanks.

Discussion (16)

Collapse
hariramjp777 profile image
Hari Ram

In programming, ++ and -- are Increment and Decrement Operators.

Say,

let a = 10;
let b = a++;
console.log(b); // 10
console.log(a); // 11
Enter fullscreen mode Exit fullscreen mode

Here, In the above code block, we're doing a++ means Post-Increment which states Set and then Increment. So, First b is set to 10 which is a 's original value and then a will be incremented by 1.

The opposite is Pre-Increment which states Increment and then Set.

let a =10;
let b = ++a;
console.log(b); // 11
console.log(a) // 11
Enter fullscreen mode Exit fullscreen mode

Hope this code block makes sense.

When you use in if-block,

say,

let num = 0;
if (num++) {  // num is zero
  console.log("Hello");
}
console.log(num); // num is 1
Enter fullscreen mode Exit fullscreen mode

"Hello" will not be printed since num is zero which is considered as false value.

If you want "Hello", you can use Pre-Increment.

let num = 0;
if (++num) {  // num is one here
  console.log("Hello");
}
Enter fullscreen mode Exit fullscreen mode

"Hello" will be printed in the console.

Falsey values in js are,

0, false, "", null, undefined, NaN

Hope it helps πŸ‘

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.

Collapse
rsa profile image
Ranieri Althoff

Hold up! Not in programming, but in Javascript and some other languages. Several languages use ++ to concatenate.

Collapse
hariramjp777 profile image
Hari Ram

Thanks. πŸ‘

Collapse
leviathanprogramming profile image
Collapse
vonheikemen profile image
Heiker • Edited

these operators in that position actually give you the "old" value back. So the expression num++ gives you a 0 (which is a falsey value).

try this in the browser console and you'll see.

var num = 0;
var result = num++;

if(result) {
  console.log('Number');
} else {
  console.log({ result, num });
}
Enter fullscreen mode Exit fullscreen mode
Collapse
leviathanprogramming profile image
π‹π„π‘½πˆπ‘¨π“π‡π€π Programming Author

I tried what you did and this:

var num = 0;
num++;
var result = num++;
if(result) {
  console.log('Number');
} else {
  console.log({ result, num });
}
Enter fullscreen mode Exit fullscreen mode

...and That answered my question. So what happens is if the number incremented by any value, the result will be true.

Collapse
vonheikemen profile image
Heiker

Every number except 0 and NaN is considered a "truthy value". And if something is "truthy" then it pass the evaluation of the if statement.

Collapse
mellen profile image
Matt Ellen • Edited

You can say, code-wise, it is equivalent to

if(val)
{
  val++;
  // do stuff
}
else
{
  val++;
}
Enter fullscreen mode Exit fullscreen mode

++ is a unary increment operator. As a postfix operator it returns the value of the object being referenced and then increments the value of the object. This means that the if statement sees the value before it is incremented.

In javascript if statements can evaluate any expression that results in a value (which I think is literally any expression), because all values are either truthy or falsey, i.e. if can treat them as boolean.

(Try evaluating if(console.log('hello')){console.log('you');}else{console.log('world');}. This works because console.log actually returns undefined, which is falsey.)

Since val++ results in a value, it can be evaluated in an if statement.

That's not a very "like I'm 5" explanation.

Imagine you have a lever you can pull. When you pull the lever there is a device that checks the contents of a box and then puts one more item in the box. (Luckily the box is similar to Mary Poppin's carpet bag.) Boxes that are not empty when checked get shot to the moon. If the box is empty when the check occurred then the only thing that happens is that there is now an item in the box.

So if you want to send an empty box to the moon you have to pull the lever twice. This also means that moon boxes have a minimum of two items in them.

The same is true for --, but there are some differences. The lever in this situation would be removing items from a box, so if there is only one item in the box, then it would go to the moon empty. Also, if the box were empty and you pull the lever twice to send it, it would have two lots of antimatter in it.

Personally I recommend against this style of programming, because you have to think about how it works way more than incrementing outside of the conditional.

Collapse
gargakshit profile image
Akshit Garg

putting ++ before a variable name means incrementing it before use, and putting it after the variable name means incrementing after use. same goes for --

So

let a = 0; // this is falsey because 0

if (a++) { // here a will be checked by if and then become 1
  console.log("I won't run, a =", a);
} else {
  console.log("I will run, a =", a); // This will print "I will run, a = 1"
}
Enter fullscreen mode Exit fullscreen mode

and

let a = 0; // this is falsey because 0

if (++a) { // here, a will become 1 before being checked with if
  console.log("I will run, a =", a); // This will print "I will run, a = 1"
} else {
  console.log("I won't run run, a =", a);
}
Enter fullscreen mode Exit fullscreen mode

Feel free to try these snippets in your browser console.

Collapse
lallenfrancisl profile image
Allen Francis • Edited

Actually none of them throw an error, both are valid javascript code.

Collapse
leviathanprogramming profile image
π‹π„π‘½πˆπ‘¨π“π‡π€π Programming Author

Yeah, I wrote that in the post, but what do they do?
I'm guessing that they test if a number has incremented?

Collapse
lallenfrancisl profile image
Allen Francis

Also I would not use this thing in an application because it's going to create a lot of bugs in the future since its hard to understand. It's best to just not use the increment operator at all and just use num += 1 or num -= 1

Collapse
lallenfrancisl profile image
Allen Francis

Oh sorry I read the -- one as error thrown. Well regarding what they do, in this particular case with num = 0 initially, the condition never becomes true and the code inside the if statement never executes. Why ? Because its post-increment and post-decrement, which means the value is only incremented in the next line of code after increment is used. Which means inside the condition check num will be still 0 and after the condition check num will become 1 or -1 respectively.

Collapse
ayabongaqwabi profile image
Ayabonga Qwabi

I think it tests if the value exists either than if its incremented or not just like if you would say if( mystring ){ do this } of if( mybool ){ do this }

Collapse
jupiteris profile image
Jupiter Programmer

I think that it is just to emphasize the means of ++a, --a

Forem Open with the Forem app