How code is written today

INPUT · Slides

Taking things out of an object

01 / 06

Near-identical lines stack up

To take a value out of an object you have written user.name. If you use it several times, you put it in a variable first.

But the more entries there are, the more near-identical lines pile up on top of each other. It is hard for the reader too: "so which ones actually get used?"

const user = {  name: "Yui",  age: 20,};const name = user.name;const age = user.age;console.log(name);console.log(age);

Result

Yui
20

02 / 06

Put { } on the left of the =

Write { } on the left side of the = and line up the names of the entries you want inside it. That alone turns those two lines into one.

This way of writing is called destructuring. It means taking the object apart and catching only the parts you need as variables.

const user = {  name: "Yui",  age: 20,};const { name, age } = user;console.log(name);console.log(age);

Result

Yui
20

03 / 06

Make the name the same as the property name

What you can write inside the { } is only the names of properties that object has. It is not that you can pick any name you like.

Write a name that is not there and it does not error; undefined goes in. The prise below is just a mistyped price, but nothing stops for you.

const book = {  title: "sky book",  price: 800,};const { prise } = book;console.log(prise);

Result

undefined

04 / 06

Take only what you need

There is no need to take everything. Just write the entries you use from here on.

Put the other way round, reading inside the { } tells you "which entries get used from here". As well as being shorter, it is a signal to the reader.

const cat = {  name: "Mofu",  color: "white",  age: 3,};const { color } = cat;console.log(color);

Result

white

05 / 06

You can write it where the argument goes

Where this shines most is a function's argument. Write { } straight in the catching place and the entries used inside show up in the function's heading.

It is a shape you see very often in other people's code, so start by being able to read it.

function introduce({ name }) {  return `hi ${name}`;}const user = { name: "Yui" };console.log(introduce(user));

Result

hi Yui

06 / 06

Let us check it all together

Tidying up what we have so far.

  • write { } on the left of the = and line up the names of the entries you want
  • make the name the same as the property name
  • write a name that is not there and you get undefined
  • it can go straight where a function's argument goes

Right — let us take some things out.