Javascript ternary operator with object
arrays, conditional-operator, javascript
Solution
Say you have
var foo = {};
The line that is confusing you would be
foo.bar = foo.bar ? foo.bar + 1 : 1; // line A
Ask yourself
- What is `foo.bar` at the start? It is undefined, we didn't give `foo` a property bar
- What is `foo.bar` after the first time line A is executed? It is `1`; `foo.bar` was undefined which is falsy so the ternary operator gave us back `1`
- What is `foo.bar` after the second time line A is executed? It is `2`; `foo.bar` was `1` which is truthy, so the ternary operator gave us back `foo.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 give `NaN`
An equally valid solution (which I find a bit cleaner to read personally) would be to do
foo.bar = (foo.bar || 0) + 1;
Problem
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.