0
function solution(first, second){
    var frequencyCounter1 = {};
    var frequencyCounter2 = {};
    for(var val of first){
    frequencyCounter1[val] = (frequencyCounter1[val] || 0) +1
   }
  console.log(frequencyCounter1);
}

I can't understand what is this syntax meaning frequencyCounter1[val] = (frequencyCounter1[val] || 0) +1

Could you do me explain this meaning?

1

1 Answer 1

0

That is a way to use the previously set value, or, if the value is falsey (either because it has never been set, or it's 0), use 0.

In this specific example, in the first iteration of the for-loop, frequencyCounter1[val] will be undefined, which is falsey, so (frequencyCounter1[val] || 0) will return 0.

It assigns the result (1) to frequencyCounter1[val], and in the next iteration, the value of frequencyCounter1[val] is 1, which is truethy, so it adds 1 + 1, etc..

An explicit example:

var object = {};

object['foo'] = (object['foo'] || 0) + 1;
// object['foo'] is undefined, so 0 is returned from the parenthesis,
// and has 1 added to it
// object['foo'] is now 1

object['foo'] = (object['foo'] || 0) + 1;
// object['foo'] is 1, so 1 is returned from the parenthesis,
// and has 1 added to it
// object['foo'] is now 2

// etc...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.