I oftentimes find that I have forgotten the object rest properties syntax.
The following is a collection of examples to which I expect to be able to refer in order to remind myself of the rules of the syntax.
Create an object.
// A flat object. Imagine a letter bank (i.e. inventory) in the game, "Words With Friends."
> let bank = {a: 1, b: 2, c: 3};Create a new object, based upon bank, using rest properties syntax.
> let newBank = {a: 4, ...bank};
> console.log(newBank);
Object {
"a": 1,
"b": 2,
"c": 3
}Notice: The a: 4 did not affect the result. Notice where the a: 4 is in our assignment (hint: it's before the rest properties operator).
Now, move the a: 4 to after the rest properties operator and repeat the experiment:
> newBank = {...bank, a: 4};
> console.log(newBank);
Object {
"a": 4, // <--
"b": 2,
"c": 3
}Notice: This time, the a: 4 affected the result!
Notice: In the following examples, we are specifying a key that does not exist on the bank object (defined above).
> newBank = {d: 4, ...bank};
> console.log(newBank);
Object {
"a": 1,
"b": 2,
"c": 3,
"d": 4 // <--
}
> newBank = {...bank, d: 4};
> console.log(newBank);
Object {
"a": 1,
"b": 2,
"c": 3,
"d": 4 // <--
}Notice: In both examples, the d: 4 affected the result (i.e. a additional property was created). Whether we put the d: 4 before or after the rest properties operator, the resulting object still contained the additional property.
- Related Babel plugin: http://babeljs.io/docs/plugins/transform-object-rest-spread/