CodeBlanks Logo Icon CodeBlanks

let and const

Learn to declare variables with let and const.

let and const

let and const are JavaScript's modern variable declaration keywords. They replace var.

A variable declared with let can be reassigned later. A variable declared with const cannot be reassigned; its value is fixed.

For example, you can write let age = 25 and then age = 26. But after const name = 'Alex', writing name = 'Sam' throws an error.

Which should you choose?

Using const by default is a good habit. If you know a variable will not change later, choose const; it tells the reader your intent.

If you know a variable will change, use let. For example, a counter or a loop variable is declared with let.

Avoid var in new Node.js code; it is old style and its scope is confusing.

Practice Declare and print variables

Use const to assign name to the string 'Alex'. Use let to assign age to the number 28. Then call console.log with each.

Starter code

index.js
// Declare name with const
// Declare age with let
// Log both

Sample solution

index.js
const name = "Alex";
let age = 28;
console.log(name);
console.log(age);

Expected output

Alex
28

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the difference between let and const?

  • const cannot change, let can Correct answer
  • They are the same
  • let cannot change, const can
  • const is only for numbers

Explanation: A const value cannot be changed later.

2 Declare with const

Question
____ version = "1.0.0";
Answer
const version = "1.0.0";

Explanation: const declares fixed values.

3 Match the declaration concepts

Term Meaning
let Mutable variable
const Fixed variable
var Old-style variable
final Not in JavaScript

All lessons in Beginner