Loops, and where your data lives

INPUT · Slides

Peeking at a value that is not there

01 / 04

When you go and fetch from nowhere

What happens if you write list[5] on an array with only two items?

It feels as though it should stop with an error, but JavaScript does not stop. It hands you back a special value called undefined.

const list = ["a", "b"];console.log(list[0]);console.log(list[5]);

Result

a
undefined

02 / 04

undefined means "nothing here yet"

undefined is the value that stands for "no value has been settled". Not 0, not the empty string "", but nothing there at all.

It is not the string "undefined" either. Write it without quotes and think of it as a special value, a cousin of true and false.

03 / 04

A property that is not there is undefined too

Objects work the same way. Ask for a name you never made and back comes undefined.

You also get undefined when you mistype a property name. If you find yourself thinking "why is nothing showing", suspect the spelling first.

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

Result

Yui
undefined

04 / 04

Following it further does give an error

undefined itself is not an error. But trying to take something further out of undefined does error and stop.

Writing list[5].name, for instance. There is nothing inside a thing that is not there.

So in the next lesson you will learn to check for undefined first and split the work safely.