Search code examples
javascriptconditional-operatorspread-syntax

Where is the truthy value for the ternary operator to execute upon in this code?


Some background for this coding problem. Our termTopics function needs to count how many times each of those topics was mentioned in the surveys, and then return an array with the number of mentions in the following order: smart city, arts funding, and then transportation.

const termTopics = (interviews) => {
  const count = interviews.reduce((acc, cv) => {
    return {...acc, [cv]: acc[cv] ? acc[cv]+1 : 1}
  }, {})
  return [count['smart city'], count['arts funding'], count['transportation']];
}

What I cannot understand is the spread operator, and how that creates a truthy statement for the ternary operator to operate with.


Solution

  • The spread syntax and the conditional operator are completely unrelated here. Let's unfold back to forth here:

    1. The entire conditional operator expression is acc[cv] ? acc[cv]+1 : 1, so it will resolve to only acc[cv]+1 or 1 based on whether or not acc[cv] is truthy or not.
    2. The result of the conditional operator is assigned to a property in an object.
    3. The property name is [cv] - a computed property name that will equal the current value of cv.
    4. The property name and value are added to an object.
    5. The rest of the object values are ...acc or the current values of the object that are spread into the object.

    In effect, {...acc, [cv]: acc[cv] ? acc[cv]+1 : 1} is a shorter version of the following ES5 code:

    var result = {};
    
    //{...acc}
    for (var key in acc) {
      result[key] = acc[key];
    }
    
    //[cv]: acc[cv] ? acc[cv]+1 : 1
    if (acc[cv]) {
      result[cv] = acc[cv]+1;
    } else {
      result[cv] = 1;
    }