Hi! This one is a little tricky for sure! Let’s break it down.
In the first line, you are simply declaring a new object ready to be used by the next line.
In the forEach, you are looking at each element (a number) in the array.
Now, let’s remember our goal: the mode is the number that appears the most often. So we need to look at each number and count how many times it appears. That is the purpose of the object we created. It will keep our count of each number. But it starts empty!
So when we look at each number, we then look to our object to see if the number is already in it as a key. If it is, we use the value side of the key:value and then add one. If it isn’t in there yet, we add it and start with zero then add one.
Hope this helps!
Also, I suggest to use console.log to see how the object changes with each pass.
However, how do you know which part of the code belongs to key, and which part belongs to value? I still don’t understand how it is able to both add the number to countand add the number of times it appeared.
@danielbailey0629 Great example! Ahh so the [ ] brackets can be used to define a key, since previous courses mostly use {key:value}.
One last question please, what is this part (counts[el] || 0) doing? It seems that if counts[el] exist, say the number is 6, it will be added by 1 to become 7?
This is sort of like the ternary operator. Going back to my example, I could have said:
newObj[“a”] = newObj[“a”] || 7;
If the first statement is undefined, you are setting a default value. This is similar to declaring a function that expects an argument but if it isn’t passed then to used a default value:
Function newFunc (arg1 = 5){}