I love when new syntax comes along which improves readability and makes code more succinct. Now I know the spread syntax isn't new to JavaScript (released with ES6) but I do feel it is underutilized. Let's take a look at a few of my common uses for this syntax.
Better array literals
Quite often I reach for the spread syntax when dealing with arrays, especially when merging two existing arrays.
let garnishes = ['orange peel', 'Luxardo cherry']
let oldFashionedIngredients = [
'rye', 'bitters', 'sugar cube', 'club soda', ...garnishes, 'ice'
]
This allows us to drop the concat
method or slice
as the above example would need.
Creating objects
I probably use the spread syntax the most when dealing with objects. Mostly when creating or cloning objects (ES2018+), but also merging objects.
let user = {
firstName: 'Benjamin',
lastName: 'Comeau'
}
let preferences = {
firstName: 'Ben',
email: true,
}
let userAndPreferences = { ...user, ...preferences }
The somewhat tricky part above is that the object on the right overrides any duplicate property values on the first object. So firstName
will actually be Ben in this case.
Function parameters
Another place I use it often is when dealing with function parameters. It easily allows one to pass an unknown amount of parameters to a function without needing to reach for .apply
, which cleans it up a bit.
let summation = (...values) => values.reduce((a, b) => a + b)
summation(1,2,3) // 6
summation(1,2,3,4,5) // 15
Hopefully you see how the spread syntax allows for more succinct code – it's syntax that I often use and enjoy seeing!