uniqueCount = ["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
var count = {};
uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});
console.log(count);
Here is the code again, but formatted using prettier.io
var uniqueCount = [
"a",
"b",
"c",
"d",
"d",
"e",
"a",
"b",
"c",
"f",
"g",
"h",
"h",
"h",
"e",
"a"
];
var count = {};
uniqueCount.forEach(function(i) {
count[i] = (count[i] || 0) + 1;
});
console.log(count);
The part your specifically asking about is this snippet:
(count[i] || 0) + 1;
Ok so lets break down the 2 parts:
(/*stuff*/) + 1
Just like normal math, stuff in ()
is executed first, along with being executed left to right. so whatever is in the ()
will be added with + 1
. Nothing fancy here.
Now lets dive into what is in ()
, and start getting into some “odd” quirks of JS that can be useful, or straight up confusing.
(count[i] || 0)
So the first part is a lookup against the count
object with the property i
.
So for the first item in the array (‘a’) we essentially are doing this:
count['a'] = (count['a'] || 0 ) + 1;
which assigns count['a']
the value of (count['a'] || 0) + 1
, which is just the value of count['a']
or 0
. So if the value at count['a']
is “truthy”, then we use it, otherwise we substitute 0.
Now lets jump into the details of how the ||
logical operator works.
Here’s the definition from mdn:
Logical OR ( ||
)
example: expr1 || expr2
If expr1
can be converted to true
, returns expr1
; else, returns expr2
.
This means is **if the first value is “truthy” then we return it, otherwise return the 2nd value.
Here is an example:
const expression1 = 'strings are true!';
const expression2 = null;
const expression3 = expression1 || expression2;
console.log(expression3); // strings are true!
const expression4 = expression2 || expression1;
console.log(expression4); // strings are true!
const expression5 = false;
const expression6 = undefined;
const expression7 = expression5 || expression6;
// the '' + will cast the value to a string so we can see it
console.log('' + expression7); //undefined
You might of expected the last example to return false
since both undefined
and false
are falsy values, but that isn’t how the ||
operator works. The same could be said for how the &&
operator works, but obviously it handles logic, and thus what is returns differently. (you can read more here)
So essentially ||
is used to “pick” between the left side or right side for the truthy value, or the last falsy value (as 0
is falsy, but since its last its “used”)
very well explained!!! respect