Spread syntax
Internally in ixfx and in demos, the spread syntax is used a lot.
Making objects
Our primary use is making objects from the basis of an existing object. This allows us to maintain immutability.
For example, let’s say we have immutable Jane. We’re not using Object.freeze()
to enforce immutability, but it’s something we’re striving for.
Her colour preference has changed to blue
. Since she’s immutable we can’t just use jane.colour = 'blue'
.
Rather, we make a new object:
Copy all the things over from jane
:
And then override or add new properties:
Properties are assigned in the listed order. If we had swapped the lines, our change would have no effect because the old colour value would overwrite the new:
In the above example we used two different variable names for clarity, but using let
would allow us to recycle the name:
Making defaults
This syntax is also helpful for having some default options which are then selectively overridden, for example:
Object.assign()
If you don’t have the spread syntax available (eg. on Espruino) you may be able to use Object.assign()
:
With Object.assign
, the first parameter is the target, the object we want to copy things to. In this case we need a new object, so {}
is provided. After that, list all the objects in order you want to copy. In the above example, first myObj
is used, then the { value: 10 }
anonymous object.
Manipulating arrays
The spread syntax can likewise be used with arrays
Function parameters
Another place you’ll see the spread operator is with functions.
This allows the function to have zero or more parameters that get passed in as a comma-separated list. In this case, we have one normal parameter, name
, and then the spread parameter, args
(but it can be called whatever you like).
Inside the function, args
is an array that can be used as normal (in this example using a for of
loop).
Spreads can be provided when calling a function too. For example, if we have an array, but the function expects a comma-separated list of parameters, we can we can spread the array: