Thursday, May 17, 2018

Don't expect foo++ or foo-- to actually change foo as a number in an assignment when making a JSON object.

In JavaScript, you must explictly use +1 and -1 in these scenarios. The ++ and the -- are legit ways to alter variables in other circumstances however. This is bad:

var foo = 6;
var yin = {
   yang: foo++
}
console.log(yin);

 
 

But, this will work...

var foo = 6;
var yin = {
   yang: foo + 1
}
console.log(yin);

 
 

...and this work too:

var foo = 6;
foo++;
var yin = {
   yang: foo
}
console.log(yin);

No comments:

Post a Comment