Assignment a number to an attribute using the += operator gives me NaN in JavaScript.
This code works as expected:
> var result = {};
undefined
> result['value'] = 10;
10
> result['value'] += 10;
20
But here we get NaN:
> var test = {};
undefined
> test['value'] += 10;
NaN
Why does JavaScript behave like this? How can I get this to work without initializing result['value'] = 0?
This line test['value'] += 10 equals to test['value'] = undefined + 10, which is NaN (Not a Number).
You can't add a number to undefined in JavaScript. If you don't want to initialize the number, you need to test if it's undefined before incrementing it:
test['value'] = (typeof test['value']==='undefined') ? 10 : test['value']+10;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With