My Favourite ES6 syntax
My favourite (and most used) not-so-new JS features are: object shorthand property names and object destructuring. Despite the similitudes in their syntax, those two features are completely unrelated (but normally, used together)
Shorthand property names #
The shorthand property name syntax allows to create an object like this:
function createPerson(name, age) {
return { name, age };
}
That is completely equivalent to this:
function createPerson(name, age) {
return { name: name, age: age };
}
Object destructuring #
Object destructuring allows to extract variables from an object:
function printAge(person) {
const { age } = person;
console.log(age);
}
It's common to use it inside function parameters. This is completely equivalent to the above:
function printAge({ age }) {
console.log(age);
}
In this way, we express clearly our intention of only using the attribute "age" of whatever comes as a parameter. We don't mind what the object is, but the shape of the object. The famous duck.
Nested property destructuring #
Destructured properties can be nested, and produce expressions like this (use with caution):
const {
pilot: { name, age },
color,
} = car;
At first can be confusing because the left side of the equal (=) looks like an object, but in fact, they are variable definitions and assignments.
The above is completely equivalent to:
const name = car.pilot.name;
const age = car.pilot.age;
const color = car.color;
Shorthand and destructuing combined #
A contrived, but close to real example:
function get('/posts/:id', async (request, response) => {
const { params: { id } } = request;
const user = await User.findOne({ where: { id } });
response.json(user);
})
Advanced destructuring #
Is good to know that arrays can be destructured too:
const [first, second] = array;
And both types can be combined:
const {
users: [{ name, age }],
ip,
} = Server;
Availability #
Shorthand property names are available since node v4 and most browsers. Destructuring is available since node 6 and IE > 11 browsers.
But both can be transpiled to be executed on older systems.
Summary #
Shorthand property names and destructuring can make the code much clear and expressive and less verbose. But destructuring is a powerful beast. It can be hard to understand and produce complex expressions, so use it with caution.