Destructuring and Spread
Often you need several properties of an object as separate variables. You could write one line for each. Destructuring does it in one line:
const employee = { name: "Alice", salary: 3000 };
const { name, salary } = employee;
console.log(name);
console.log(salary);
Output:
Alice
3000
The braces on the left side of = are a pattern. They mean "make a variable for each of these keys, and copy the value from the object". The variable names must match the keys, but the order does not matter. const { salary, name } = employee; gives the same result.
If a key is missing, its variable is undefined. You can give it a default value with =:
const { dept = "none" } = employee;
console.log(dept);
Output:
none
Arrays can be destructured too. With square brackets, the variables are filled by position instead of by key:
const pair = ["laptop", 12];
const [product, count] = pair;
console.log(product, count);
Output:
laptop 12
You will use this array form in the next lesson, to unpack key and value pairs in a loop.
Destructuring also works in the parameters of a function. The caller passes the whole object, and the function takes out only the properties it needs:
function describe({ name, salary }) {
return `${name} earns ${salary}`;
}
const bob = { name: "Bob", salary: 2800, age: 41 };
console.log(describe(bob));
Output:
Bob earns 2800
The three dots ... that you used to copy arrays also work inside an object. { ...employee } makes a new object with all the properties of employee. Add a property after the spread, and it replaces the copied one:
const employee = { name: "Alice", salary: 3000 };
const promoted = {
...employee,
salary: employee.salary + 500,
};
const wrong = { salary: 3500, ...employee };
console.log(promoted);
console.log(wrong);
console.log(employee);
Output:
{ name: 'Alice', salary: 3500 }
{ salary: 3000, name: 'Alice' }
{ name: 'Alice', salary: 3000 }
When the same key appears twice, the later one wins. So the new salary must come after ...employee. In wrong, it comes first, and the copied salary of 3000 replaces it.
The original employee did not change. This matters for the same reason as with arrays. Other parts of a program may hold a reference to the original object, and they still see the old data, unchanged. Making an updated copy, instead of changing the original, is a very common pattern in modern JavaScript.
In the exercise, destructure an employee, then use spread to make a copy with a raise.