Objects and Arrays in ES6
ES6 has some new tools for dealing with objects and arrays. These include destructuring assignment, enhanced object literals and the spread operator.
Destructuring Assignment
Object destructuring
Object destructuring allows us to pull in specific attributes from an object and scope it locally. Consider the following cat object (also known as an object literal).
We can pull out attributes and create local variables out of them. These variables can be changed without changing the original cat
object.
Just as object literals allow us to create multiple properties at once, we can destructure them, by extracting multiple properties at once. This is considered an object pattern.
This is the same thing as doing the following in ES5.
We can also destructure objects that are arguments in functions. Consider the following function that logs the cats gender.
This is the same thing as doing the following;
Instead of using dot notation to access the color of the cat object literal within the function, we can destructure the cat object and pull out it’s color attribute.
This is a more declarative approach because we signal that we are only using the color attribute from the cat object.
Array destructuring
In ES6 we can pull out values from arrays and scope them to local variables.
You can pass over values in arrays using commas to get to specific indexes.
You can get all the remaining elements of an array using the rest operator. This operator looks like the spread operator in ES6 (…) except it is used inside function calls and arrays.
You can use array destructuring to swap values in variables.
This is the same as the following in ES5.
Enhanced Object Literals
Object literal enhancement allows us to create objects from variables that are in scope.
color
and age
are now attributes in the new cat object. Object literal enhancement can also include functions.
We can write a shorthand version of this without the function operator.
We can write shorthand for objects whose properties are initialised by variables of the same name.
This is the same as writing the following in ES5.
This could be quite handy in functions or modules that export objects.
This is the same as writing the following in ES5.
Spread Operator
The spread operator is three dots (…) and allows us to do powerful new things with arrays.
Copy
We can copy arrays.
The array copy animalsCopy
is separate from the animals
array and is unaffected by changes to animalsCopy
.
This is a great way to deal with immutable data that uses arrays.
Function arguments
The spread operator can be used in functions to collect arguments as an array. Consider this use of appply
.
This can be called in ES6 using the spread operator like this;
Inversely, we can create a function that accepts n
number of arguments as an array then uses the spread operator to operate on them.
-
I highly recommend using the Babel Repl to play around with ES6 code.