I came across a piece of code I am trying to figure out, the code basically stores the occurrence of the amount of time a word appears in a text document, so the function countWordsIntext takes in the desired text and displays the word and the number of occurrence in the text, e.g would: 3 but: 5 very: 6
while looking at the function that counts the word in the text I cant figure out how the conditional tenary operation is supposed to work. An explanation would be very much appreciated
var wordCounts = {};
function countWordsInText(text) {
var words = text.toString()
.toLowerCase()
.split(/\W+)
.sort();
for(var index in words) {
var word = words[index];
if(word) {
wordCounts[word] =
(wordCounts[word]) ? wordCounts[word] + 1 : 1;
}
}
}
function display()
{
for (var index in wordCounts)
console.log(index + ': ' + wordCounts[index]);
}
I don't understand how the wordCounts[word] object property is updated.
Say you have
The line that is confusing you would be
Ask yourself
foo.barat the start? It is undefined, we didn't givefooa property barfoo.barafter the first time line A is executed? It is1;foo.barwas undefined which is falsy so the ternary operator gave us back1foo.barafter the second time line A is executed? It is2;foo.barwas1which is truthy, so the ternary operator gave us backfoo.bar + 1Line A can be repeated until you run out of numbers or the world explodes
Writing it like this is a way to solve the
undefined + 1problem, which would giveNaNAn equally valid solution (which I find a bit cleaner to read personally) would be to do