Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning using += gives NaN in javascript

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?

like image 682
jsbisht Avatar asked Feb 06 '15 14:02

jsbisht


2 Answers

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

like image 165
Lewis Avatar answered Sep 19 '22 21:09

Lewis


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;
like image 32
Blazemonger Avatar answered Sep 17 '22 21:09

Blazemonger