Skip to content

Beginner · First steps: values, variables and operators · topic 3 of 61 · 20 min

Variables: let, const and var

Explanation

A variable is a name for a value. Use const when the name will always point to the same value, and let when you need to assign a new value later. var is the old way; it ignores blocks and allows confusing mistakes, so avoid it in new code.

Why variables?

Programs need to remember things: a price, a user name, a running total. A variable is a name that refers to a value, so you can use the value later and give it a meaning. total is much clearer than writing 1499 + 250 + 99 again and again.

Declaring and assigning

Declaring means creating the name. Assigning means giving it a value with the = sign. You can do both in one line. = in JavaScript does not mean "is equal to"; it means "put the value on the right into the name on the left".

javascript
let cartItems = 0;      // declare and assign
cartItems = cartItems + 1;  // assign a new value
cartItems += 2;             // short form of cartItems = cartItems + 2
console.log(cartItems);     // 3

const GST_RATE = 18;        // never changes
console.log(GST_RATE);      // 18

const: the binding cannot change

const means the NAME is locked to one value; you cannot assign to it again. A binding is the link between a name and a value. If the value is an object or array, its contents can still change. const locks the link, not the object.

javascript
const prices = [100, 200];
prices.push(300);       // allowed: the same array, changed inside
console.log(prices);    // [100, 200, 300]

prices = [1, 2];        // TypeError: Assignment to constant variable.
const stops reassignment, not changes inside an object or array.

let: when the value must change

Use let for counters, running totals, and values you update in a loop. Both let and const are block-scoped: a block is the code between { and }, and a let or const made inside a block does not exist outside it.

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

Why not var?

var was the only way before 2015. It has three problems. It ignores blocks (it is function-scoped), so a var inside an if leaks out. It can be declared twice without any error. And it is hoisted, which means you can use it before the line that declares it and silently get undefined. You will see old code with var, so you must be able to read it, but do not write it.

javascript
if (true) {
  var leaked = 'oops';
}
console.log(leaked);   // 'oops' (var ignores the block)

var count = 1;
var count = 2;         // no error with var
console.log(count);    // 2

Naming rules and style

  • Names may use letters, digits, _ and $, but cannot start with a digit (2total is invalid).
  • Names are case-sensitive: total and Total are different.
  • Reserved words like let, class or return cannot be names.
  • Use camelCase for normal variables (orderTotal, isPaid) and UPPER_SNAKE_CASE for fixed settings (MAX_RETRIES).
  • Booleans read well with is/has/can: isLoggedIn, hasCoupon.
Think of it like this: A const variable is like the name plate on your house gate: once it is fixed to this house, it stays. People inside the house can rearrange furniture (change an object's contents), but the plate does not move to another house. A let variable is like a sticky note you can move to a different box whenever you want.
Careful: Forgetting let or const creates an accidental global variable in old non-strict code (total = 5 with no keyword). In strict mode and in modules it is a ReferenceError instead. Always declare variables with const or let.
Tip: Rule of thumb used by most teams: write const by default. Change it to let only when the code needs to reassign. Never use var.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Variables: let, const and var · 1/6

Variables

In this lesson you will store values in variables using let and const.

Prefer a video by a teacher? Find free videos on “javascript let const var difference explained” on YouTube ↗

In real life: An EMI calculator

A bank's loan page keeps the interest rate and loan amount in const variables because they do not change during one calculation. The remaining balance changes every month, so it is a let variable that is updated in a loop.

javascript
const principal = 100000;     // loan amount in rupees
const monthlyPayment = 9000;
let balance = principal;
let months = 0;
while (balance > 0) {
  balance -= monthlyPayment;
  months += 1;
}
console.log('Paid off in', months, 'months');
Prints Paid off in 12 months (interest ignored to keep it simple).

Practice (0/2 done)

Task 1 · Code · Javascript

Fix this code. It should end with total equal to 60, but it crashes because total is declared with const and then changed. Change the declaration so the code works.

Task 2 · Code · Javascript

Write a function addToCart(cart, item) that pushes item into the cart array and returns the new number of items. The cart is declared with const outside; you should change the array's contents, not reassign it.

Quick quiz

Question 1

1.const list = [1]; list.push(2); What happens?

Question 2

2.Which keyword should you use by default for new variables?

Question 3

3.if (true) { let a = 1; } console.log(a); What happens?

Question 4

4.Which is a valid variable name?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

const list = [1]; list.push(2); What happens?

Answer: list becomes [1, 2]

const stops reassignment of the name, not changes inside the array.

Which keyword should you use by default for new variables?

Answer: const

Use const by default and switch to let only when you must reassign.

if (true) { let a = 1; } console.log(a); What happens?

Answer: ReferenceError

let is block-scoped, so a does not exist outside the braces.

Which is a valid variable name?

Answer: orderTotal

Names cannot start with a digit, cannot contain -, and cannot be reserved words like class.

What value does a declared variable have before you give it one?Related

Answer: undefined

A let variable without a value is undefined.

From Values, types and variables

const int Max = 10; Max = 20; What happens?Related

Answer: Compile error: a const cannot be changed

A const value is fixed at compile time and cannot be assigned again.

From Types and variables

A loop with var i pushes () => i three times. Calling them gives [3, 3, 3]. Why?Related

Answer: var makes one i for the whole function, shared by all the functions

All three functions see the same i, which is 3 when the loop ends. let gives each round its own i.

From Scope, hoisting and closures

Which is a valid variable name?Related

Answer: total_marks

Names cannot start with a digit, cannot contain spaces, and cannot be keywords like class.

From Variables: giving names to values

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “First steps: values, variables and operators” before its exam: Operators and type coercion, Numbers and Math.
  2. Module 1 exam: First steps · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Strings, decisions and loops. 61 topics left in the course before the final exam.

← Previous: Values and types