DEV Community

Cover image for Spread Operator and Chaining in JS/TS
Grant Riordan
Grant Riordan

Posted on

Spread Operator and Chaining in JS/TS

Hey, so I’m sometimes asked how the spread operator works in JS especially when working with chained statements.

Some confuse the ... (spread) operator as applying to the first element of the chain, spreading the variable before applying chained functions.

This isn’t correct; it applies to the result of the chain.

Take this code:

const getLongestWordLength = (sentence: string) => {
  return Math.max(
    ...sentence
      .replace(/\./g, "")
      .split(" ")
      .map((word) => word.length)
  );
};
Enter fullscreen mode Exit fullscreen mode

Some may think it spreads the sentence variable first then applies the other chained functions, which you would be right in thinking would throw an error.

However, due to the way that JS works the . operator is seen as what's called a primary expression, meaning it takes *precedence * over every other operator.

This would be the same as if you wrote your code like this, wrapping your statement in brackets:

const getLongestWordLength = (sentence: string) => {
  return Math.max(
    ...(sentence
      .replace(/\./g, "")
      .split(" ")
      .map((word) => word.length))
  );
};
Enter fullscreen mode Exit fullscreen mode

But fortunately for us these extra brackets aren't needed due to the . expression precedence.

So in fact what the code is doing is:

  1. Replace all . in a string.
  2. Split the result on spaces.
  3. Return the length of each word.
  4. Spread the lengths array to Math.max()

Code is read left to right, treating the chain as a single variable / element - so no need to wrap our statement in extra brackets.

Hope this helps 😁 - did you know this?

Top comments (0)