For the most part, programming means managing data. A lot of data. This job is mostly about assembling and disassembling objects, joining them, dividing them, passing them on to functions.
Boring, isn’t it? Luckily ES6 came to our rescue with a lot of new features that make the job much easier for us. And funny. We have already talked about the “three dots thing” (see the spread operator), now let’s talk about destructuring in javascript.
Let’s immediately see an example (no, it is not a variable assigned backward):
const { name, director, year } = movie
Well, what’s that movie
? it’s an object like this:
const movie = {
name: "The Searchers",
director: "John Ford",
year: "1956"
}
Now if we try to log the variables, we will get the three values of corresponding keys on the object.
console.log(name, director, year)
// The Searchers John Ford 1948
So nice. Let’s go ahead and see other useful examples. Take for an array:
const movie = ["The Searchers", "Rio Bravo"]
In the old javascript if I had wanted to refer to the first of the two elements I would have done:
movie[0]
To avoid this syntax, in ES6 I could do
const [first, second] = movie
console.log(first)
// The Searchers
We can also set default values to avoid undefined variables
const movie = {
name: "The Searchers",
director: "John Ford"
}
const { name, director, genre = 'western' } = movie
console.log(`"${name}" is a ${genre} movie by ${director}`)
// "The Searchers" is a western movie by John Ford
We can also use this functionality to manage nested objects
const movie = {
name: "The Searchers",
year: "1956",
scores: {
photography: 10,
screenplays: 8
}
}
const { name, scores: {photography, screenplays} } = movie
console.log(`"${name}" scores: ${photography}, ${screenplays}`)
//"The Searchers" scores: 10, 8
Star Trek The Next Generation. Season Three.