var: Grandpa's Old Box

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

If you look at older JavaScript code online (anything written before about 2015), you'll see variables created with a third keyword: var.

JavaScript
var color = "blue";
console.log(color);

It prints

blue

var was the only way to create variables for the first twenty years of JavaScript's life. It still works today. But it has some odd behaviors that can cause sneaky bugs. For example, var lets you create the same variable twice without any complaint, which can lead to accidentally overwriting something important:

JavaScript
var score = 100;
var score = 0;   // no error! The old score is silently wiped out.
console.log(score);

It prints

0

There are a few other quirks too (they're about something called scope, which you'll master in Grade 9). That's why modern JavaScript introduced let and const in 2015 as better replacements.

Note

In this book, we never use var for new code. But you should recognize it, because you'll definitely bump into it in tutorials, old projects, and answers on the internet. When you see var, just think "old-school let" and you'll be fine 99% of the time.

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