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, they are used together).
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 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.
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;
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);
})
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
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.
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.
Here's another JavaScript bits we wanted to share with you. Small tips and tricks for JavaScript developers for all levels. This time around, we share how to return more than one value.
Read full articleHere's another JavaScript bits we wanted to share with you. 10 things to remember when coding.
Read full articleHere's another JavaScript bits we wanted to share with you. Let's talk about the comparison operator, today.
Read full article