0

I am practicing js and i encounter this line of code in a for each loop

function test(arr1){
  let fq1 = {}

  for(val of arr1){
    fq1[val] = (fq1[val] || 0) + 1
  }
}

test([1,2,3,3]);

i have provided the code what i encounter can anyone please exaplian what is happening in

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

i tried and i have seen the object key is storing the number of value are provided in array. But i am not clear about the line of code i have mentioned above.

flyingfox
  • 13,414
  • 3
  • 24
  • 39
mrshiam
  • 13
  • 6

1 Answers1

1
(fq1[val] || 0)

this means evaluate to the value on the left if it is truthy (if converted to a boolean, it would be true), otherwise evaluate to the value on the right.

In this specific case, this is saying "evaluate to the value in object fq1 at key val, however if it's undefined (not in the object yet) then use 0 as a default value"

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34