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)
);
};
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))
);
};
But fortunately for us these extra brackets aren't needed due to the .
expression precedence.
So in fact what the code is doing is:
- Replace all
.
in a string. - Split the result on spaces.
- Return the length of each word.
- 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)