Declaring, Assigning, and undefined

Grade 1, page 6 of 9. A one-minute read.

Here's something interesting. You don't have to put a value into a let box right away. You can create an empty box now and fill it later:

JavaScript
let favoriteSong;
console.log(favoriteSong);

favoriteSong = "Happy Birthday";
console.log(favoriteSong);

It prints

undefined
Happy Birthday

Whoa, what's undefined?

When you create a variable without giving it a value, JavaScript puts a special value called undefined inside. It means "this box exists, but nothing has been put in it yet." It's JavaScript's way of saying "¯\\\_(ツ)\_/¯".

This gives us some useful vocabulary:

  • Declaring a variable means creating the box: let favoriteSong;
  • Assigning a value means putting something in the box: favoriteSong = "Happy Birthday";
  • Initializing means doing both at the same time: let favoriteSong = "Happy Birthday";
Watch outUsing a box that doesn't exist

undefined (the box exists but is empty) is different from a variable that was never created at all:

JavaScript
console.log(favoriteMovie);

It stops with an error

Uncaught ReferenceError: favoriteMovie is not defined

"Not defined" means "there's no box with that label anywhere." This usually happens because of a typo. Check that the spelling and capital letters match exactly where you created the variable!

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning