JavaScript Tutorial · JavaScript Basics · Lesson 5 of 44

JavaScript Variables

Declare variables with let and const — and why to avoid var.

let and const

Variables are named containers for values.

  • const declares a variable that cannot be reassigned. Use it by default.
  • let declares a variable you will reassign later.
Example 1Try it yourself
const name = "Ada";
let score = 10;
score = score + 5;
console.log(name, score);

Output

Ada 15

Trying to reassign a const throws TypeError: Assignment to constant variable.

const doesn't mean frozen

const protects the binding, not the value. An object or array declared with const can still be changed:

Example 2Try it yourself
const user = { name: "Ada" };
user.name = "Grace";      // allowed: changing a property
const colors = ["red"];
colors.push("blue");      // allowed: changing the array
console.log(user, colors);

Output

{ name: 'Grace' } [ 'red', 'blue' ]

What about var?

var is the old way to declare variables. It is function-scoped instead of block-scoped and is hoisted, which leads to confusing bugs. Modern code uses only let and const.

Example 3Try it yourself
for (var i = 0; i < 3; i++) {}
console.log("var i after the loop:", i);  // var leaks out of the block

for (let j = 0; j < 3; j++) {}
console.log(typeof j);  // let stays inside the block

Output

var i after the loop: 3
undefined

Naming rules

  • Use descriptive camelCase names: userCount, not uc.
  • Constants that are truly fixed configuration are often written in UPPER_SNAKE_CASE: const MAX_RETRIES = 3;

Test yourself

Which keyword should you use by default for variables that are never reassigned?

  1. var
  2. let
  3. const
  4. static
Show answer

Answer: const