Assigning using += gives NaN in javascript

This line test['value'] += 10 equals to test['value'] = undefined + 10, which is NaN (Not a Number).


This happens because you're trying to add 10 to an undefined property of your object, so your line will result in doing:

test['value'] = undefined + 10; // NaN

Every numerical expression which causes an unknown value turns into NaN (not a number) in JavaScript. To make it work, you should check if that property exists and has a numerical value, then add some number to it; otherwise you'll have to create it. Plus, since that you're working with an object, you can use test.value instead of test['value'].

Here is an example:

if (Number(test.value)) test.value += 10;
else test.value = 10;

// Or more neatly:
test.value = +test.value ? test.value + 10 : 10;

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;