DEV Community

loading...

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

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