A quirky way to dynamically set key/value pairs in Javascript

There are many instances where we’re tasked to keep a running tally of how frequently an element occurs within an array. Some examples include constructing an algorithm that determines whether or not a given word or string can be rearranged to form a palindrome, or whether or not two given strings or numbers have the same frequency of letters/numbers.

Let’s set up a basic example. Suppose you’re given an array of fruits (Apples, oranges, grapes, etc.) and your job is to determine whether or not there is the same number of each fruit within the given array. A good first step would be the following:

const countFruits = (fruitsArray) => {
  let counts = {};

  for (fruit of fruitsArray) {
    counts[fruit] += 1;
  }

  console.log(counts);
}

The problem you will run in to is that counts[fruit] += 1 is going to cause an error in that whatever the current value of fruit is during that iteration does not yet exist within the counts object. You’re essentially trying to add one to undefined. The above will give you an object that has the fruits listed as keys – but each value of those keys will be NaN.

We can use this to our advantage, however. Here is the ‘quirky’ approach that we can incorporate because if counts[fruit] has not been initialized it DOES NOT RETURN A TRUTHY VALUE

  for (fruit of fruitArray) {
    counts[fruit] = counts[fruit] + 1 || 1;
  }

By using the logical OR (||) operator we can evaluate whether or not the value exists, and if it does not already exist simply set the value to 1 during the first iteration. The next time our loop encounters that same key it will already be set to 1 and it will simply increment it by 1.