Nothing Yet With null and undefined

You’ve met undefined before without being formally introduced. The Node REPL prints it after every const line you type, and in Turn Numeric Text Into Numbers, typeof undefined showed that it has a type of its own. In this lesson, you’ll find out what that value means.

Picture the planning stage of your hike. Some answers aren’t known yet. You haven’t weighed the new stove, and you haven’t picked a campsite. A program needs a way to hold “nothing here yet” without pretending it’s a real weight or a real name.

JavaScript has two values for that job, undefined and null. In this lesson, you’ll learn where each one comes from, how they differ from 0 and empty text, and what they do in a calculation. Then you’ll use null in a script of your own.

Meet undefined, the Value Nobody Assigned

So far, you’ve given every variable a value when you created it. With let, you can also create a variable and leave out the = and its value. JavaScript still creates the variable.

Start the Node REPL by typing node in the integrated terminal. Then create a variable for the stove you haven’t weighed and ask for its value:

Language: JavaScript
> let stoveKg
undefined
> stoveKg
undefined
> typeof stoveKg
'undefined'

The first undefined is the REPL’s usual reply after a line that creates a variable, just as you’ve seen after const lines. The second one is different. It’s the value stored in stoveKg, and typeof confirms that its type is 'undefined'.

So undefined is the value a variable holds when nothing has been assigned to it yet. You didn’t write it anywhere. JavaScript filled it in for you.

Once you weigh the stove, you can assign a value with =, as you did with the assignment operator in Ask Whether Two Values Are the Same. Type this line next:

Language: JavaScript
> stoveKg = 0.4
0.4
> stoveKg
0.4

There’s no let this time, because stoveKg already exists in this REPL. From now on, it holds a real number, and undefined is gone.

Choose null When Something Is Empty on Purpose

The campsite is a different situation. You know you haven’t picked one, and you want your script to say so clearly. For that, JavaScript has a second value, null, which means “deliberately empty.” You write it yourself, as a plain word without quotes, just like true and false.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.