Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 156 ยท Getting Started

Variables: let, const and var

Declare JavaScript variables with let and const, learn naming rules, why const objects can still change, why to avoid var, and what the temporal dead zone is.

Programs work with data: a user's name, the items in a cart, the current score. To keep a value around and use it later, you store it in a variable. A variable is a name that points to a value, like a label on a box.

JavaScript has three keywords for creating variables: let, const and the older var. In this lesson you will learn when to use each, how to name variables well, and a few subtle rules that explain some confusing error messages.

Declaring a variable

Creating a variable is called declaring it. You write a keyword, a name, and usually an = sign followed by the starting value:

JavaScript
let score = 0;
const playerName = "Kofi";

The = here means "store this value", not "is equal to". Giving a variable its first value is called initializing it. Once a variable exists, you use it by writing its name:

JS Creating and using variables

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The line score = score + 10 puts mathematics aside: JavaScript first calculates the right side using the current value (0 + 10), then stores the result back in score. Changing a variable's value like this is called reassigning it. Notice that you only write let once, when the variable is declared.

let and const

The two modern keywords differ in one way:

  • let creates a variable you can reassign later.
  • const creates a variable that can never be reassigned. It must get its value immediately.
JavaScript
let lives = 3;
lives = 2;           // fine

const maxLives = 3;
maxLives = 5;        // TypeError: Assignment to constant variable.

const startLevel;    // SyntaxError: const needs an initial value

Which one should you use? Most experienced developers follow a simple rule: use const by default, and switch to let only when you know the value must change, such as a counter or a running total. Most variables in real programs never get reassigned, and const tells every reader "this name always means the same value", which makes code easier to follow.

You can declare a let variable without a value. It then holds undefined until you assign something:

JavaScript
let winner;
console.log(winner); // undefined
winner = "Team Blue";

You can also declare several variables in one statement, separated by commas (let x = 1, y = 2;), but one declaration per line is easier to read and is the style used in this course.

const with objects and arrays

Here's a detail that confuses many beginners. const stops you from reassigning the variable, but it doesn't freeze the value it points to. If that value is an object or an array, you can still change what's inside it:

JS const protects the name, not the contents

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Think of const as gluing the label to one particular box. You can rearrange the contents of the box as much as you like, but you can't move the label to a different box. You'll learn why objects behave this way in Data Types, and how to actually freeze an object in Working with Objects.

Naming variables

Variable names (identifiers) follow a few hard rules:

  • They can contain letters, digits, underscores _ and dollar signs $.
  • They can't start with a digit: player1 is fine, 1player is not.
  • They can't contain spaces or hyphens: total-price would be read as total minus price.
  • They can't be reserved words such as let, class, return or new.
  • They are case-sensitive: total and Total are different variables.

And a few conventions that every JavaScript developer follows:

  • Use camelCase for variables and functions: start lowercase and capitalize each new word, as in itemCount, isLoggedIn or firstOrderDate.
  • Use PascalCase for classes: ShoppingCart.
  • Some teams use UPPER_SNAKE_CASE for fixed configuration values known before the program runs, such as const MAX_UPLOAD_MB = 25;.
  • Name booleans like questions: isVisible, hasAccount, canEdit.

Above all, choose names that describe the value. const d = 7; makes the reader guess; const deliveryDays = 7; explains itself. A slightly longer, clear name is almost always better than a short, cryptic one.

Why to avoid var

Before 2015, var was the only way to declare a variable. You will still find it in older code and tutorials, so you should recognize it, but there is no reason to use it in new code. It behaves differently from let and const in three ways that cause bugs:

  1. It ignores blocks. A var declared inside an if block or a loop is visible outside it. let and const stay inside their block.
  2. It can be declared twice. Writing var total a second time silently reuses the same variable, which hides mistakes. Declaring the same let twice is an error.
  3. It's hoisted with the value undefined. You can use a var before the line that declares it and get undefined instead of a helpful error.
JS var leaks out of blocks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

There is also a fourth quirk: a var declared at the top level of a classic script becomes a property of the global window object, where it can clash with other scripts. let and const don't do that. The Scope and Hoisting lesson explains all of this in depth.

The temporal dead zone

let and const variables also exist from the start of their block, but you can't touch them until the line that declares them has run. The stretch of code before that line is called the temporal dead zone (TDZ). Using the variable there throws a ReferenceError with a message like "Cannot access 'x' before initialization":

JS The temporal dead zone

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This error is a feature: it stops you from accidentally using a value that hasn't been set yet, which is exactly the bug var lets through. The fix is to declare variables before you use them, which is also the most readable order. Swap the two const lines above and the code works.

Redeclaring stops the whole script. If you write let price = 1; and later let price = 2; in the same block, you get a SyntaxError. Syntax errors are found before any code runs, so not even the first line executes. That's different from the errors above, where the lines before the error ran normally.

Variables without a keyword

If you assign to a name that was never declared, such as count = 5;, a classic script quietly creates a global variable. That's almost always a typo, and in strict mode, which modules and classes use automatically, it throws a ReferenceError instead. Always declare your variables with const or let.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which keyword should you use for a variable that will never be reassigned?

    Use const by default. It prevents reassignment and tells readers the name always refers to the same value.
  2. 2. What happens here? const list = [1, 2]; list.push(3);

    const only prevents reassigning the variable. The array it points to can still be changed, so push works.
  3. 3. Which variable name is invalid?

    Identifiers can contain digits but can't start with one. The others use allowed characters.
  4. 4. What does console.log(city); let city = "Oslo"; do?

    let and const variables can't be used before their declaration runs. With var, you would get undefined instead, which hides the bug.
  5. 5. Why is var best avoided in modern code?

    var still works everywhere, but it is function-scoped, can be declared twice and is hoisted with undefined. let and const avoid all three problems.

Summary

  • A variable is a name for a value. Declare it with const or let and give it a value with =.
  • const can't be reassigned and needs a value right away; let can be reassigned. Prefer const and use let only when the value must change.
  • const doesn't freeze objects or arrays: their contents can still change.
  • Names may use letters, digits, _ and $, can't start with a digit, and are case-sensitive. Use descriptive camelCase names.
  • Avoid var: it ignores blocks, allows redeclaration and is hoisted as undefined.
  • Using a let or const before its declaration throws an error: the temporal dead zone.

Next: The Console and First Debugging Steps โ€” logging, tables and reading error messages.