0

I am practicing counting the frequency of unique elements in an array using this function, which I found here on StackOverflow:

let numArray = [1,3,8,10,39,67,88,12,11,9,1,8,1,8]
let countFrequency = function(arr){
     var counts = {};
     for (var i = 0; i < arr.length; i++) {
          var num = arr[i];
          counts[num] = counts[num] ? counts[num] + 1 : 1;
          }
console.log(counts)
}

and then calling the function like so:

countFrequency(numArray);

And the result is this: {"1":3, "3":1, "8":3,...etc} which is correct and the desired behaviour.

However. I have no idea why this works and what is happening 'under the hood'. This is a common solution here on StackOverflow for this type of problem, but I can't find a clear explanation of this line:

counts[num] = counts[num] ? counts[num] + 1 : 1;

I know this is a ternary operator and how the operator itself works, but cannot for the life of me understand how it is building the 'counts' object. Could anyone please explain exactly how this solution works, or point me in the direction of an article that explains this? I think this would be useful for others who are learning this technique too, so thanks in advance!

0

1 Answer 1

3

If you try to read a property which does not exist it returns undefined, which is falsey in javascript. So, with that in mind lets expand the ternary to a longhand if statement

if(counts[num]){
   counts[num] = counts[num] + 1;
}
else {
   counts[num] = 1
}

Hopefully that makes it clearer what is going on, in pseudocode

if counts[num] has previously been set
   add one to counts[num]
otherwise
   set counts[num] to 1

One other thing that might have thrown you is the square bracket notation for reading properties. In javascript both myObject.foo and myObject["foo"] are equivalent.

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

4 Comments

for exists, the reprensentation is in. you need to introduce falsy ...
@NinaScholz Sorry, didn't understand your comment.
counts[num] could be undefined as value or as state, or any other falsy value, or any other truthy value. the check for an existing key is in (i think, you know it all, but the answer does not represent this)
@NinaScholz technically correct. In this specific case/piece of code we equate truthiness with the existance of the value, as we don't expect any falsy values; only undefined when the value is absent. So counts either doesn't contain num or it contains a truthy value for num. And I agree with you that this distinction is important and a JS programmer should be introduced to it. Im just not sure if this doesn't go too much beyond the scope of this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.