javascript

1.8 JavaScript Let, Const, Var

Learn the core differences between `let`, `const`, and `var` in JavaScript. Understand their scope, reassignment rules, and when to use each for cleaner, safer code.

10 min read 8 sections Tutorial
Share

In JavaScript, **variables** are like named containers for storing data. You use them to hold numbers, text, or other information that your program needs. To create these containers, you use special keywords: `let`, `const`, and `var`. Each keyword has its own rules for how the variable behaves, especially about changing its value and where it can be used in your code.

1.8 JavaScript Let, Const, Var

1.8 JavaScript Let, Const, Var

A variable is a named storage location. It holds a value that your program can use or change. Imagine it as a box with a label on it. You can put things into the box, take things out, or replace what's inside.

JavaScript offers three keywords to declare variables: let, const, and var. Understanding their differences is key to writing good, modern JavaScript code. This tutorial will explain each one simply.

What are let, const, and var?

let, const, and var are keywords used to declare (create) variables in JavaScript. They tell the computer to reserve a spot in memory and give it a name so you can store and retrieve values.

let

Declares a variable whose value can be changed later. It is 'block-scoped'. Use this for most variables that might update.

const

Declares a constant variable whose value cannot be reassigned after its initial creation. It is also 'block-scoped'.

var

The old way to declare variables. It has 'function-scope' and behaves differently, often leading to confusion. Avoid using it in new code.

Best Practice

Modern JavaScript prefers let and const. Using them helps prevent common programming mistakes and makes code clearer.

Declaring Your First Variable

Getting Started

Declaring Your First Variable

To declare a variable, you write the keyword (let or const), then the variable's name, then an equals sign =, and finally the value you want to store. The equals sign is for assignment, meaning 'put this value into this variable'.

Once a variable is declared, you can use its name to access the value. For let variables, you can also change the value later.

javascript
1// Declare a variable named 'score' using let. Its value can change.
2let score = 0;
3
4// Print the current value of score.
5console.log("Initial score:", score); // Output: Initial score: 0
6
7// Change the value of 'score'. This is allowed with let.
8score = 100;
9
10// Print the new value of score.
11console.log("New score:", score); // Output: New score: 100
12
13// Declare a constant named 'MAX_ATTEMPTS' using const. Its value cannot change.
14const MAX_ATTEMPTS = 3;
15
16// Print the value of MAX_ATTEMPTS.
17console.log("Max attempts:", MAX_ATTEMPTS); // Output: Max attempts: 3
18
19// If you try to change MAX_ATTEMPTS, it will cause an error.
20// MAX_ATTEMPTS = 5; // Uncommenting this line would cause a TypeError

Declare Before Use

Always declare your variable using let or const before you try to use it. If you try to use a variable that hasn't been declared, JavaScript will give you a ReferenceError because it doesn't know what you are talking about. It's like trying to open a box that doesn't exist yet.

How Let and Const Handle Values

How Let and Const Handle Values

The main difference between let and const is whether you can change the variable's value after it's been set. With let, you can assign a new value to the variable whenever you want. This is called reassignment.

With const, once you give it a value, that value is locked. You cannot reassign a new value to a const variable. If you try, JavaScript will stop your program with a TypeError.

javascript
1// Using let for a player's health
2let playerHealth = 100;
3console.log("Player health starts at:", playerHealth); // 100
4
5// Player takes damage, health changes
6playerHealth = 80;
7console.log("Player health after damage:", playerHealth); // 80
8
9// Using const for a game setting
10const GAME_TITLE = "Space Explorer";
11console.log("Game title:", GAME_TITLE); // Space Explorer
12
13// Try to change the game title (this will cause an error)
14// GAME_TITLE = "Galaxy Quest"; // Uncommenting this line will cause a TypeError
15// console.log("New game title:", GAME_TITLE);
✗ BadWrong: Reassigning a const
const gameLevel = 1;
gameLevel = 2; // ❌ TypeError: Assignment to constant variable.
console.log(gameLevel);
✓ GoodCorrect: Reassigning a let
let gameLevel = 1;
gameLevel = 2; // ✅ Works fine.
console.log(gameLevel); // 2

Choosing Between let and const

Choosing Between let and const

Deciding whether to use let or const is a very common task. The simple rule is: if the variable's value will never change after its first assignment, use const. If the variable's value might change, use let.

Many developers follow a 'prefer const' rule. This means they start by declaring every variable with const. If they later find out they need to change that variable's value, they then switch it to let. This approach helps prevent accidental changes and makes your code more predictable.

Use let when values change
// A counter that increases
let count = 0;
count = count + 1;
// A user's name that can be updated
let userName = "Guest";
userName = "Alice";
// A flag that toggles true/false
let isLoading = true;
isLoading = false;
VS
Use const for fixed values
// A mathematical constant
const PI = 3.14159;
// A base URL for an API
const API_BASE_URL = "https://api.example.com";
// Configuration settings
const MAX_ITEMS = 100;
// An array or object (you can change its contents, but not reassign the array/object itself)
const colors = ["red", "green"];
colors.push("blue"); // This is allowed!
// colors = ["yellow"]; // This would be an error!

The 'Prefer const' Rule

A good habit is to always start with const. If your code later needs to reassign that variable's value, then (and only then) change it to let. This makes your code safer and clearer by explicitly marking which values are not meant to change.

Understanding var (and why to avoid it)

Understanding var (and why to avoid it)

var is the oldest keyword for declaring variables in JavaScript. It was the only option before let and const were introduced in 2015. While it still works, var has some confusing behaviors that can lead to bugs, especially for beginners.

The main issues with var are its function scope and hoisting. These behaviors are different from let and const, which have block scope. We will explore what these terms mean.

1

var has Function Scope

A variable declared with var is visible throughout the entire function it is declared in, even inside if statements or for loops. This is different from let and const, which are only visible within the specific block (like an if block or loop) where they are defined.

javascript
1function greeting() {
2 if (true) {
3 var message = "Hello!"; // var is function-scoped
4 }
5 console.log(message); // ✅ Works! message is visible outside the if block
6}
7greeting();
2

var allows Redeclaration

You can declare the same var variable multiple times in the same scope without an error. This can accidentally overwrite values, leading to bugs that are hard to find. let and const prevent this by throwing an error if you try to redeclare them.

javascript
1var count = 10;
2console.log(count); // 10
3
4var count = 20; // ✅ No error, 'count' is redeclared and overwritten
5console.log(count); // 20
3

var is Hoisted

Variables declared with var are 'hoisted' to the top of their function scope. This means JavaScript processes their declaration before your code actually runs. However, only the declaration is hoisted, not the assignment. So, if you try to use a var variable before its assignment, it will be undefined, not an error.

javascript
1console.log(userName); // Output: undefined (not an error!)
2var userName = "Alice";
3console.log(userName); // Output: Alice
4
5// For let/const, this would be a ReferenceError:
6// console.log(userAge); // ❌ ReferenceError
7// let userAge = 30;

Why Avoid var?

Because of its function scope, redeclaration allowance, and hoisting behavior, var can make code harder to understand and debug. It can lead to variables unintentionally leaking out of blocks or being accidentally overwritten. Modern JavaScript avoids these issues by using let and const for cleaner and more predictable code.

Keyword Comparison & Best Practices

Keyword Comparison & Best Practices

KeywordCan Reassign?ScopeAllows Redeclaration?
letYesBlock ScopeNo (throws error)
constNoBlock ScopeNo (throws error)
varYesFunction ScopeYes

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which keyword should you use for a variable whose value will not change after it's first set?

Quick Check

What will happen if you try to reassign a value to a const variable?

Quick Check

Which of these variable declarations has 'Block Scope'?

Quick Check

What is a common reason to avoid using var in modern JavaScript development?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1let — Use for variables whose values might change. It has block scope.
  • 2const — Use for variables whose values will not change. It also has block scope.
  • 3var — The old way to declare variables. Avoid it in new code due to its function scope and hoisting.
  • 4Block Scope — Variables are only accessible within the {} block where they are defined (for let and const).
  • 5Function Scope — Variables are accessible throughout the entire function (for var).
  • 6Reassignmentlet allows you to change its value. const does not, throwing a TypeError if you try.
  • 7Redeclarationvar allows redeclaration (overwriting a variable), let and const do not (throwing an error).
  • 8Hoistingvar declarations are hoisted (moved to the top of their scope) and initialized as undefined. let and const are also hoisted but are not initialized, leading to a ReferenceError if accessed before declaration.
  • 9Prefer const — A good practice is to use const by default, and only switch to let if you know the variable's value needs to change.
  • 10Naming Rules — Variable names must start with a letter, underscore _, or dollar sign $. They cannot contain spaces or special characters (except _ and $).

JavaScript Scope

Deep dive into global, function, and block scope to understand variable visibility.

JavaScript Data Types

Explore the different kinds of values variables can hold, like numbers, strings, and booleans.

JavaScript Functions

Learn how to write reusable blocks of code and how variables work within them.

JavaScript Operators

Understand how to perform calculations and comparisons using your variables.

You've Mastered Variable Declarations!

You now understand the crucial differences between let, const, and var. You can confidently choose the right keyword for your variables, write safer code, and avoid common pitfalls. This knowledge is fundamental to becoming a skilled JavaScript developer!

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning