Increment operator returns NaN
-
25-10-2019 - |
Question
I am trying to increment a variable using the ++
operator but I keep getting NaN
as a result and I'm not sure why. Here is my code:
var wordCounts = { };
var x = 0
var compare = "groove is in the heart";
var words = compare.split(/\b/);
for(var i = 1; i < words.length; i++){
if(words[i].length > 2){
wordCounts["_" + words[i]]++;
}
}
alert(wordCounts.toSource());
Solution
The value of wordCounts["_" + words[i]]
is initially undefined
so when you ++ it, it gives you NaN. Just change your code to:
if (wordCounts["_" + words[i]]) {
wordCounts["_" + words[i]]++;
} else {
wordCounts["_" + words[i]] = 1;
}
OTHER TIPS
Try something like...
var key = "_" + words[i];
if (wordCounts[key]) {
wordCounts[key]++
} else {
wordCounts[key] = 1;
}
You are trying to increment undefined
which is giving you NaN
.
To be able to use the ++
operator (which takes a number and increments it by one) the target needs to have a number first.
Attempt a check to see if the object is defined, and if not initialize it by setting it's value to 1.
if ('undefined' === typeof wordCounts["_" + words[i]]) {
wordCounts["_" + words[i]] = 0;
}
Something like:
var wordCounts = {};
var x = 0
var compare = "groove is in the heart";
var words = compare.split(/\b/);
for (var i = 1; i < words.length; i++) {
if ('undefined' === typeof wordCounts["_" + words[i]]) {
wordCounts["_" + words[i]] = 0;
}
if (words[i].length > 2) {
wordCounts["_" + words[i]]++;
}
}
alert( JSON.stringify( wordCounts ) );
What you're basically doing is
undefined++
Which will result in...
NaN
Try...
wordCounts["_" + words[i]] = (wordCounts["_" + words[i]]++ || 1);
Since NaN
is a "falsey" value the || will fall back to 1.
You're trying to increment an object (wordCounts[]++) it's not a number so it can't be incremented, which is why you're getting that error. What are you actually trying to do (in plain English)?