Describe your issue in detail here.
Can someone please explain how the array.forEach() is working here.
counts[el] = (counts[el] || 0) + 1;
when I log counts, it has the numbers entered as values and the how many times the numbers have been repeated as the keys. And I have 0 idea on how thats happening with 1 single line of code here.
Hi!
This line is trying to set the value of the counts object where the key is the number “el”. If there isn’t already a key with that number, it assumes the value is zero. The second step adds 1 to either the value at that key, or zero. The third step assigns this new value to that key.
So in the parentheses, counts[el] could be undefined, and if so, the algorithm then assumes the value zero.
Assume array = [“2”,“2”,“3”] and counts ={}. Then the forEach runs:
counts[“2”] = (counts[“2”] || 0) + 1
What happens? It is setting the key “2” equal to something. This is perfectly fine code and how we often set a key value pair in an object. What is the “something”? The first thing we encounter is trying to retrieve the value from the key “2”, but it doesn’t exist yet! So it returns undefined. In which case the || takes over and the value becomes 0. Then we add 1. So counts = {“2”: 1}.
Next pass: counts[“2”] = (counts[“2”] || 0) + 1. Now the value at “2” is 1, so the || 0 is ignored, and add 1 for a value of 2. Counts = {“2”: 2}.
Final pass: counts[“3”] = (counts[“3”] || 0) +1. There is no key of “3”, so it is undefined so the || 0 takes over then we add 1. Counts = {“2”: 2, “3”:1}.