Modern JavaScript has a couple of lovely shortcuts for working with objects.
Shorthand properties
If you're making an object from variables that have the same names as the keys you want, you can skip the repetition:
const name = "Nina";
const age = 21;
const city = "Barcelona";
const longWay = { name: name, age: age, city: city };
const shortWay = { name, age, city };
console.log(shortWay);
It prints
{ name: 'Nina', age: 21, city: 'Barcelona' }{ name } is short for { name: name }. Less typing, same result.
Destructuring
Destructuring goes the other way: it pulls properties out of an object and into separate variables, all in one line:
const movie = { title: "Black Panther", year: 2018, rating: 7.3 };
// the long way
const title1 = movie.title;
const year1 = movie.year;
// the destructuring way
const { title, year, rating } = movie;
console.log(title);
console.log(year);
console.log(rating);
It prints
Black Panther 2018 7.3
The curly braces on the left side of the = say: "make variables called title, year and rating, and fill them with the matching properties from movie."
You can also rename variables and give them default values:
const movie = { title: "Black Panther", year: 2018 };
const { title: movieName, director = "unknown" } = movie;
console.log(movieName);
console.log(director);
It prints
Black Panther unknown
Arrays can be destructured too, using square brackets. Items are picked out by position:
const podium = ["Zoe", "Kenji", "Leah"];
const [gold, silver, bronze] = podium;
console.log(`🥇 ${gold} 🥈 ${silver} 🥉 ${bronze}`);
It prints
🥇 Zoe 🥈 Kenji 🥉 Leah
Destructuring in function parameters
Remember the Grade 6 advice to avoid functions with too many parameters? Here's the solution. Pass one object instead, and destructure it right in the parameter list:
function createAccount({ username, email, isAdmin = false }) {
console.log(`Created ${username} (${email}). Admin: ${isAdmin}`);
}
createAccount({ email: "emma@example.com", username: "emma" });
createAccount({ username: "boss", email: "boss@example.com", isAdmin: true });
It prints
Created emma (emma@example.com). Admin: false Created boss (boss@example.com). Admin: true
Now the order doesn't matter (we passed email first in the first call, and it still worked), every argument is clearly labeled, and optional ones can have defaults. This pattern is used everywhere in professional JavaScript.