# Confused with this syntax

Let’s assume I need a function to get the frequency of the vals of an array, the output should be an object of key value pairs representing how many times a val is repeated in the given arr, the order doesn’t matter. Example:

[1, 3, 4, 1] expected output: {1: 2, 3: 1, 4: 1}
[2, 3, 5, 3] expected output: {2: 1, 3: 2, 5: 1}

``````function getFrequency(arr) {
let freqCounter = {}
for(let val of arr) {
// I am confused as how this line of code works
freqCounter[val] = (freqCounter1[val] || 0) + 1;
//
}
return freqCounter;
}
``````

How exactly is that line working, normally I would do it as followed:

``````for(let val of arr) {
freqCounter[val] = freqCounter[val] ? ++frequencyCounter[val] : 1;
}
``````

Can someone explain to me how are those lines doing the same thing?

Oh and by the way, does anybody know of an online tool to measure algorithms time complexity (Big O)?

If `freqCounter1` is truthy, then it will be used. If falsy, then 0 will be used.

Basically, when the `||` is used, it returns the value of the second operand if the first one is falsy, otherwise, the value of the first operand is returned.

FYI - If you wanted a more functional approach you could do something like:

``````const getFrequency = arr => arr.reduce((obj, key) => ({ ...obj, [key]: (obj[key] || 0) + 1 }), {});
``````
1 Like

Thank you sir, I think I get it now. So basically in the first iteration (considering this as the input `[1, 3, 4, 1]`) because 1 doesn’t exist as a prop in the freqCounter object, 0 will be used as the value of 1, plus 1, then in the final iteration it’s going to be `truthy` because 1 already exists and we just add 1 to its current val.

It’s good that I finally understand the operation, however I do feel using a basic ternary operator is just easier to read, well at least for less inexperienced programmers such as myself.

Anyways, thanks again.

Clever functional approach,. it has a small flaw though. It’s one of the drawbacks of a JS objects.

You would have to use Map() instead.

Example:
[1, 3, 4, 1, ‘1’] would give {1: 3, 3: 1, 4: 1} which is incorrect.

All keys are strings with object literals.

True, if the array had both strings and numbers.

I still like it though. First time I’ve seen that pattern.