Loops, and where your data lives

INPUT · Slides

Checking for undefined and stepping around it

01 / 05

Shown as it is, it says nothing

In the last lesson you saw that showing a missing property gets you undefined on the screen.

If a person reads undefined, they have no idea what happened. When there is no value, show something that says so.

02 / 05

Check it with === undefined

Write === undefined as the condition of an if and you can build work that only happens "when there is no value".

Write undefined without " around it. Wrapped in quotes it becomes a string and will never match, so take care.

const list = ["a", "b"];if (list[5] === undefined) {  console.log("no such number");}

Result

no such number

03 / 05

Split off the normal case with else

Add an else and you have written both "when there is nothing" and "when there is".

Deal with the empty case first to get it out of the way, then use the value with confidence — written that way it reads well.

const user = { name: "Haruto" };if (user.nickname === undefined) {  console.log(user.name);} else {  console.log(user.nickname);}

Result

Haruto

04 / 05

You can make "there is" the condition instead

Write !== undefined and the condition becomes "when there is a value". Choose whichever reads better.

Use it inside a loop and you can skip the missing data and add up the rest.

const nums = [10, 20];let total = 0;for (let i = 0; i < 4; i++) {  if (nums[i] !== undefined) {    total += nums[i];  }}console.log(total);

Result

30

05 / 05

Writing to protect yourself

Checking for undefined is also a guard that keeps the program from stopping.

Use something that is not there and it errors and stops; check first and you can step around it safely. In a real app you will write this constantly. Let us practise from here.