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
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.
1// Declare a variable named 'score' using let. Its value can change.2let score = 0;34// Print the current value of score.5console.log("Initial score:", score); // Output: Initial score: 067// Change the value of 'score'. This is allowed with let.8score = 100;910// Print the new value of score.11console.log("New score:", score); // Output: New score: 1001213// Declare a constant named 'MAX_ATTEMPTS' using const. Its value cannot change.14const MAX_ATTEMPTS = 3;1516// Print the value of MAX_ATTEMPTS.17console.log("Max attempts:", MAX_ATTEMPTS); // Output: Max attempts: 31819// 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.
1// Using let for a player's health2let playerHealth = 100;3console.log("Player health starts at:", playerHealth); // 10045// Player takes damage, health changes6playerHealth = 80;7console.log("Player health after damage:", playerHealth); // 8089// Using const for a game setting10const GAME_TITLE = "Space Explorer";11console.log("Game title:", GAME_TITLE); // Space Explorer1213// Try to change the game title (this will cause an error)14// GAME_TITLE = "Galaxy Quest"; // Uncommenting this line will cause a TypeError15// console.log("New game title:", GAME_TITLE);
const gameLevel = 1;gameLevel = 2; // ❌ TypeError: Assignment to constant variable.console.log(gameLevel);
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.
// A counter that increaseslet count = 0;count = count + 1;// A user's name that can be updatedlet userName = "Guest";userName = "Alice";// A flag that toggles true/falselet isLoading = true;isLoading = false;
// A mathematical constantconst PI = 3.14159;// A base URL for an APIconst API_BASE_URL = "https://api.example.com";// Configuration settingsconst 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!
// A counter that increaseslet count = 0;count = count + 1;// A user's name that can be updatedlet userName = "Guest";userName = "Alice";// A flag that toggles true/falselet isLoading = true;isLoading = false;
// A mathematical constantconst PI = 3.14159;// A base URL for an APIconst API_BASE_URL = "https://api.example.com";// Configuration settingsconst 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.
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.
1function greeting() {2 if (true) {3 var message = "Hello!"; // var is function-scoped4 }5 console.log(message); // ✅ Works! message is visible outside the if block6}7greeting();
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.
1var count = 10;2console.log(count); // 1034var count = 20; // ✅ No error, 'count' is redeclared and overwritten5console.log(count); // 20
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.
1console.log(userName); // Output: undefined (not an error!)2var userName = "Alice";3console.log(userName); // Output: Alice45// For let/const, this would be a ReferenceError:6// console.log(userAge); // ❌ ReferenceError7// 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
| Keyword | Can Reassign? | Scope | Allows Redeclaration? |
|---|---|---|---|
| let | Yes | Block Scope | No (throws error) |
| const | No | Block Scope | No (throws error) |
| var | Yes | Function Scope | Yes |
Test Your Knowledge
Test Your Knowledge
Which keyword should you use for a variable whose value will not change after it's first set?
What will happen if you try to reassign a value to a const variable?
Which of these variable declarations has 'Block Scope'?
What is a common reason to avoid using var in modern JavaScript development?
Quick Reference
Quick Reference
- 1
let— Use for variables whose values might change. It has block scope. - 2
const— Use for variables whose values will not change. It also has block scope. - 3
var— 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 (forletandconst). - 5Function Scope — Variables are accessible throughout the entire function (for
var). - 6Reassignment —
letallows you to change its value.constdoes not, throwing aTypeErrorif you try. - 7Redeclaration —
varallows redeclaration (overwriting a variable),letandconstdo not (throwing an error). - 8Hoisting —
vardeclarations are hoisted (moved to the top of their scope) and initialized asundefined.letandconstare also hoisted but are not initialized, leading to aReferenceErrorif accessed before declaration. - 9Prefer
const— A good practice is to useconstby default, and only switch toletif 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.