How code is written today

INPUT · Slides

Following an entry that may not be there

01 / 05

You cannot follow past something that is not there

Taking out an entry that is not there only gave back undefined; the program did not stop.

But try to follow further from that undefined and it stops right there. Write user.address.city for a user with no address and this is what you get.

const user = { name: "Yui" };console.log(user.address.city);

Result

TypeError: Cannot read properties of undefined (reading 'city')

02 / 05

With ?. it does not stop

Write ?. instead of . and when the left side is not there it breaks off and gives back undefined. It does not go on following, so there is no error.

Read it as "if it is there, on we go; if not, undefined".

const user = { name: "Yui" };console.log(user.address?.city);

Result

undefined

03 / 05

When it is there it behaves the same

Write ?. and when it is there it is exactly the same as .. The value comes out as usual.

Which is to say, ?. is a device that only works "when it was not there". It does not get in the way of everyday reading and writing.

const user = {  name: "Yui",  address: { city: "Harbourtown" },};console.log(user.address?.city);

Result

Harbourtown

04 / 05

Do not put it everywhere

Handy as it is, turning every . into a ?. is not a good idea. Because when something that really should be there is missing, it goes quietly on too.

Then the undefined gets carried along to lines far away and you cannot tell where things broke. Stopping with an error finds the cause much faster.

Write ?. only where you know it is possible for something to be missing. That is how to use it.

05 / 05

Decide the stand-in for when it is missing

What ?. gives back is undefined, so you can judge it with === undefined as always. Decide the display for when it is missing yourself.

Follow without stopping, then swap in a word if it was not there. This two-stage build is the shape you write most in practice. Let us write from here.

const user = { name: "Haruto" };const city = user.address?.city;if (city === undefined) {  console.log("not registered");} else {  console.log(city);}

Result

not registered