by Matt Granmoe
How to simplify your code with the spread operator
bar is passed. But somehow prevent returning
bar is not passed, since some usages of this in the codebase don’t pass it. He was specifically looking for a way to do this that wouldn’t require any refactoring (like changing from an implicit return to a full function body, using if/else, creating a separate function to do filtering of certain values, etc).
Here’s a condensed example to throw in the console if you want:
This is possible due to two things. First, the fact that, although the spread operator can’t occur anywhere as a token, it can be applied to literally any data type in the entire language.
It’s commonly known that
Set and similar are iterable. The fact that all primitive types are also valid operands of the spread operator allows us to spread literally any expression since all expressions will evaluate to some value after being executed.
If you don’t believe me, throw the following in the console:
The second thing that helps us is that spreading an “empty” value results in a no-op.
- Guard expressions (à la React’s JSX, and also what was used to solve the original problem mentioned in this post):
...(foo && parseFoo(foo))
- “Default” expressions:
...(someValue || someDefault)
A more generic way to refer to all these things might be “spread expressions.” However, I’d now like to say “spread expressions” not as a noun but as a suggestion. Go forth with the knowledge that you can spread all the expressions! 😄