Skip to content

Instantly share code, notes, and snippets.

@gitname
Last active June 24, 2017 02:44
Show Gist options
  • Save gitname/db24f1716f0f801c7b21e8abaadb48e1 to your computer and use it in GitHub Desktop.
Save gitname/db24f1716f0f801c7b21e8abaadb48e1 to your computer and use it in GitHub Desktop.
Object Rest Properties Syntax for ECMAScript/JavaScript - Examples

Introduction

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.

Examples

Flat Object

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};

Order of Properties

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!

Adding a Property

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.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment