DEV Community

loading...

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

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.