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:

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:

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.