Declaring variables

Topic 1 of 5 in Variables & types9 min readBeginnerFree course

Overview

A variable is a name for a value. Instead of writing the same value again and again, you give it a name once and use the name everywhere. If the value changes, you only update it in one place — and the name tells readers what the value means.

JavaScript gives you three ways to declare a variable: const, let and the older var.

JavaScript
const course = 'JavaScript Essentials';
let lessonsDone = 3;
lessonsDone = lessonsDone + 1;
console.log(lessonsDone); // 4

Declaring, assigning and reading

Working with a variable involves three steps, which you’ll often do in one line:

JavaScript
let score;          // 1. declare: create the name (its value is undefined)
score = 10;         // 2. assign: store a value in it
console.log(score); // 3. read: use the value → 10

let lives = 3;      // declare and assign together (most common)

You can declare several variables in one statement, separated by commas, but one per line is easier to read:

JavaScript
let x = 0, y = 0;   // allowed
let width = 100;    // clearer
let height = 50;

const and let

Use const when the name will always point to the same value. Use let when you need to reassign it later.

Three examples. const max points to 10 and cannot be pointed at 11 — that throws a TypeError. let visits first points to 0 and then to 1. const user points to an object whose name property can still change from Asha to Ravi.

It helps to think of a variable as a label attached to a value, rather than a box that contains it. const glues the label to one value for good; let lets you move the label to a different value.

JavaScript
const max = 10;
max = 11; // TypeError: Assignment to constant variable.

let visits = 0;
visits = visits + 1; // fine
visits += 1;         // the same thing, shorter

A const must be given its value immediately, because it can never be assigned later:

JavaScript
const answer; // SyntaxError: Missing initializer in const declaration

const doesn’t freeze objects. You can’t point a const at a new object, but you can still change the object’s properties or push items into an array. To truly lock an object, use Object.freeze() — covered in Equality and immutability.

JavaScript
const user = { name: 'Asha' };
user.name = 'Ravi';        // allowed — the object changed, not the label
user = { name: 'Mina' };   // TypeError — that would move the label

const tags = ['js'];
tags.push('web');          // allowed

Which one should I use?

Start every variable as const. If you later find you need to reassign it, change it to let. In practice most variables in good code are const, and when you see a let, it’s a useful signal: this value is going to change, keep an eye on it.

Naming variables

Variable names can contain letters, digits, _ and $, but cannot start with a digit, and cannot be reserved words such as let, class or return.

JavaScript
let userName;     // ✓ camelCase — the JavaScript convention
let _private;     // ✓
let $element;     // ✓
let 2ndPlace;     // ✗ starts with a digit
let user-name;    // ✗ dash means minus
let class;        // ✗ reserved word

Good names make code read like a sentence:

Instead of Prefer Why
d daysUntilDue Says what it holds
data orders Specific
flag isLoggedIn Booleans read well with is, has, can
arr selectedIds Plural names for lists

By convention, values that are fixed for the whole program — configuration, magic numbers — are sometimes written in UPPER_SNAKE_CASE: const MAX_UPLOAD_MB = 10;.

Block scope

let and const only exist inside the block where they were declared — the nearest pair of curly braces. This area is called the variable’s scope.

A function contains let total and a var. Inside an if block, const discount only exists within that block; total is visible in the whole function including inner blocks; var code escapes the block to the whole function.

JavaScript
if (true) {
  const message = 'inside';
  console.log(message); // 'inside'
}
console.log(message); // ReferenceError: message is not defined

Inner blocks can see variables from outer blocks, but not the other way round. Two separate blocks can each have their own variable with the same name, without clashing:

JavaScript
for (let i = 0; i < 2; i++) { /* this i … */ }
for (let i = 0; i < 2; i++) { /* … and this i are different */ }

The temporal dead zone

A let or const exists from the start of its block, but you can’t use it until the line that declares it has run. Using it too early throws an error. That stretch of code is nicknamed the temporal dead zone:

JavaScript
console.log(price); // ReferenceError: Cannot access 'price' before initialization
const price = 9.99;

This is a good thing — it turns a likely bug into a clear error. You’ll learn more in Scope and hoisting.

Why not var?

var is how variables were declared before 2015. It has two behaviours that make bugs easy to write:

  1. It ignores blocks. A var is scoped to the whole function (or the whole script), so it “leaks” out of if blocks and loops.
  2. It is hoisted with the value undefined. You can read it before it’s declared and get undefined instead of an error.
JavaScript
if (true) {
  var leaked = 'oops';
}
console.log(leaked); // 'oops' — visible outside the block

console.log(early);  // undefined — no error, just a silent bug
var early = 5;

var also lets you declare the same name twice without complaint, so you can accidentally overwrite a variable. Modern code uses let and const instead. You’ll still see var in older tutorials and libraries, so it’s worth recognising.

const let var
Can reassign No Yes Yes
Scope Block Block Function
Use before declaration Error Error undefined
Redeclare in same scope Error Error Allowed
Use in new code ✓ default ✓ when needed ✗

Undeclared variables

If you assign to a name you never declared, older non-strict code silently creates a global variable. That’s almost always a typo:

JavaScript
let counter = 0;
countr = 1; // creates a global "countr" in sloppy mode; ReferenceError in strict mode

Strict mode and modules turn this into an error, which is one more reason to use them.

Exercise

Pick the right keyword

Rewrite this so that values which never change use const, and give the vague variable a descriptive name.

JavaScript
let siteName = 'Academy';
let visits = 0;
let x = 20;
visits = visits + 1;
console.log(`${siteName}: ${visits} of ${x} visits`);

Summary

  • Use const by default and let when the value must change.
  • const stops reassignment, not changes inside an object or array.
  • Both are block-scoped — they only exist inside the nearest { }.
  • Using a let/const before its declaration throws (the temporal dead zone).
  • Avoid var in new code; it is function-scoped and hoisted.