Purixi Purixi - 3 months ago 5
Javascript Question

What am I doing wrong with arrays?

I'm pretty new to the JavaScript as well as to the Node.JS and I really can't understand why I'm getting NaN using the following expression:

var aUsersBetted = {};
aUsersBetted['1337'] += 200000;

After doing this it prints me NaN in console. I'm really confused now. Sorry for the dumb question by the way.


Let's take it line by line.

This var aUsersBetted = {}; creates an object, not an array.

This aUsersBetted['1337'] += 200000; adds 200000 to the value that is associated with the key 1337.

Since, you haven't defined the key before you use it, it's value is also undefined. So you try to add to an undefined value to a number. That's why you get this error.

One possible workaround to your problem it would be to initialize the value of 1337, like:

aUsersBetted['1337'] = 0;

Then your expression, aUsersBetted['1337'] += 200000;, would add 200000 to 0 and set this to the back to the place in memory, where aUsersBetted['1337'] points to.