Skip to content
Advertisement

Understanding how javascript evaluates the OR operator

I’m currently studying Javascript Algorithms. Below is the algorithm im currently trying to learn/understand.

function same(arr1, arr2){
    if(arr1.length !== arr2.length){
        return false;
    }
    let frequencyCounter1 = {}
    let frequencyCounter2 = {}
    for(let val of arr1){
        frequencyCounter1[val] = (frequencyCounter1[val] || 0) +1
        console.log(frequencyCounter1);
    }
    for(let val of arr2){
        frequencyCounter2[val] = (frequencyCounter2[val] || 0) +1        
    }


    for(let key in frequencyCounter1){
        if(!(key ** 2 in frequencyCounter2)){
            return false
        }
        if(frequencyCounter2[key ** 2] !== frequencyCounter1[key]){
            return false
        }
    }
    return true
}

same([1,2,3,2,5], [9,1,4,4,11])

I understand the code, except for 1 line.

frequencyCounter1[val] = (frequencyCounter1[val] || 0) +1

So what this algo does, is it tries compares 2 arrays. If array b is equal to the square of each number is array a, then it should return true, else it will return false.

So in this example, it will return false

If i do [1,2,3,4,5] [1,4,9,16,25], it will return true

I know what this line does:

frequencyCounter1[val] = (frequencyCounter1[val] || 0) +1

It makes a key value pair, so say for the first iteration, it makes take in 1 as the key and then (frequencyCounter1[val] || 0) +1 as the value, now this value represents the number of a times a number appears in array so if 1 appears 10 times it’ll have a key value pair 1:10

I understand this very clearly, just wanted to know how this statement is evaluated and whats happening behind the scenes?

(frequencyCounter1[val] || 0) +1

Advertisement

Answer

The idea is that if frequencyCounter1[val] is undefined it defaults to 0. undefined + 1 returns NaN and it wouldn’t work as the programmer intended, so he uses || to workaround that problem without having to write additional lines of code.

In JavaScript the operator || doesn’t return true or false as you would expect, it returns either the first element that would evaluates as true if it was converted to boolean, or default to the last element if none is found.

For example, (null || "" || undefined || false || NaN || "test" || 2) will return "test"

Advertisement