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.bar
at the start? It is undefined, we didn't givefoo
a property barfoo.bar
after the first time line A is executed? It is1
;foo.bar
was undefined which is falsy so the ternary operator gave us back1
foo.bar
after the second time line A is executed? It is2
;foo.bar
was1
which is truthy, so the ternary operator gave us backfoo.bar + 1
Line 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 + 1
problem, which would giveNaN
An equally valid solution (which I find a bit cleaner to read personally) would be to do