javascript tip

Managing objects

Destructuring is a huge part of ES6 and something you're probably going to be using often. It allows us to extract data from objects, and assigning the extracted data into variables:

const rectangle = { h: 100, w: 200 };
const { h, w } = rectangle;

We can rename the variables if we want to:

const { h: height, w: width} = rectangle;
console.log(height); // 100

Another handy thing we could do is to destructure the returned object by a function and pick and choose what values we want to use:

function getPerson() {
  return {
    firstName: 'Max',
    lastName: 'Best',
    age: 42
  }
}

const { age } = getPerson();
console.log(age); // 42

So, with destructuring, we can return multiple values from a function by returning an object and choosing the pieces we want to be returned. Removing a property in an immutable way requires a little trick provided by spread’s counterpart, the rest operator, which is written with three dots (...) like spread. However, in this case, we spread the remaining properties into a new object.

const { age:_ , ...person } = getPerson();

console.log(person); // {firstName: "Max", lastName: "Best"}

Now the person object holds all properties from the original person object except age.