When you write code, you often need to change the value of a variable. Sometimes, you might even try to create the same variable name again. This tutorial explains two important ideas: **re-declaration** and **re-assignment**. You will learn how `let`, `const`, and `var` behave differently when you try to declare a variable more than once or change its value. Knowing these rules helps you avoid mistakes and write better JavaScript.
Re-declaration and Re-assignment
Re-declaration and Re-assignment
In JavaScript, a variable is like a labeled box that holds a value. You create this box using keywords like let, const, or var.
Re-declaration means trying to create a new box with the same label (variable name) again. It's like trying to put two labels with the same name on two different boxes in the same spot.
Re-assignment means taking the value out of an existing box and putting a new value inside it. It's like taking out a toy from a box and putting a different toy in the same box.
Key Terms Defined
Re-declaration: Declaring a variable with the same name more than once in the same scope.
Re-assignment: Changing the value of an already declared variable.
let
Cannot be re-declared, but can be re-assigned. This makes it very flexible and safe.
const
Cannot be re-declared and cannot be re-assigned (for primitive values). It is for fixed values.
var
Can be re-declared and re-assigned. This old behavior often leads to unexpected bugs.
Why it matters
Understanding these rules prevents errors and helps you choose the right keyword for your variables.
What are Re-declaration and Re-assignment?
What are Re-declaration and Re-assignment?
Let's look at a simple example to see the difference. When you first create a variable, you are declaring it. You also usually assign it a value at the same time.
If you later want to put a new value into that variable, you are re-assigning it. You are not creating a new variable, just changing what's inside the existing one.
1// This is a DECLARATION: We create a variable named 'score'2// We also ASSIGN it an initial value of 1003let score = 100;4console.log("Initial score:", score); // Output: Initial score: 10056// This is a RE-ASSIGNMENT: We change the value inside the existing 'score' variable7// We are NOT declaring a new variable, just updating the old one8score = 200;9console.log("Updated score:", score); // Output: Updated score: 2001011// If we tried to DECLARE 'score' again with 'let', it would be an error12// let score = 300; // This line would cause an error!
Declaration vs. Assignment
Remember, declaration means creating the variable for the first time using let, const, or var. Assignment means giving a value to a variable, whether it's the first time or later. Re-assignment is just changing an existing value.
How `let` Handles Re-declaration and Re-assignment
How `let` Handles Re-declaration and Re-assignment
The let keyword was added to JavaScript to be safer and clearer than var. With let, you can easily change the value of a variable after you declare it. This is called re-assignment.
However, let does not allow you to declare the same variable name twice in the same part of your code. If you try to re-declare a let variable, JavaScript will give you an error. This is a good thing because it helps prevent accidental mistakes where you might overwrite a variable you already created.
1// 1. Declare and assign a 'let' variable2let userName = "Alice";3console.log("Original userName:", userName); // Output: Original userName: Alice45// 2. Re-assign the 'let' variable (this is allowed)6userName = "Bob";7console.log("Re-assigned userName:", userName); // Output: Re-assigned userName: Bob89// 3. Try to re-declare the 'let' variable (this causes an error)10// let userName = "Charlie"; // ❌ Uncaught SyntaxError: Identifier 'userName' has already been declared1112// JavaScript stops you from making this mistake, which is helpful.
let gameScore = 100;let gameScore = 200; // ❌ Error!console.log(gameScore);
let gameScore = 100;gameScore = 200; // ✅ Works!console.log(gameScore); // 200
How `const` Handles Re-declaration and Re-assignment
How `const` Handles Re-declaration and Re-assignment
The const keyword stands for 'constant'. This means its value should stay fixed once it's set. Because of this, const is even stricter than let.
Like let, you cannot re-declare a const variable. Trying to do so will give you a SyntaxError. More importantly, you also cannot re-assign a const variable to a new value after it has been created. If you try, JavaScript will throw a TypeError.
// 1. Declare and assign a 'const' variableconst PI = 3.14159;console.log("PI value:", PI);// 2. Try to re-assign the 'const' variable (this causes an error)// PI = 3.14; // ❌ Uncaught TypeError: Assignment to constant variable.// This prevents accidental changes to important fixed values.
// 1. Declare a 'const' objectconst user = { name: "Alice", age: 30 };console.log("User object:", user);// 2. You CAN change properties of the objectuser.age = 31; // ✅ This is allowed!console.log("Updated user age:", user.age);// You cannot re-assign 'user' to a NEW object, but you can change what's inside the existing object.
// 1. Declare and assign a 'const' variableconst PI = 3.14159;console.log("PI value:", PI);// 2. Try to re-assign the 'const' variable (this causes an error)// PI = 3.14; // ❌ Uncaught TypeError: Assignment to constant variable.// This prevents accidental changes to important fixed values.
// 1. Declare a 'const' objectconst user = { name: "Alice", age: 30 };console.log("User object:", user);// 2. You CAN change properties of the objectuser.age = 31; // ✅ This is allowed!console.log("Updated user age:", user.age);// You cannot re-assign 'user' to a NEW object, but you can change what's inside the existing object.
const with Objects and Arrays
Remember that const prevents you from re-assigning the variable itself to a completely new value. But if the const variable holds an object or an array, you can still change the properties of that object or the items in that array. You just cannot make the const variable point to a different object or array entirely.
How `var` Handles Re-declaration and Re-assignment
How `var` Handles Re-declaration and Re-assignment
The var keyword is the oldest way to declare variables in JavaScript. It behaves differently from let and const and can be a source of confusion and bugs. Modern JavaScript code almost always avoids var.
With var, you can re-declare a variable with the same name without any error. You also can re-assign a var variable to a new value. This flexibility might seem good, but it often leads to accidentally overwriting variables you thought were safe.
Declare and Assign `var`
First, we declare a variable using var and give it a value.
1var counter = 10;2console.log("Initial counter:", counter); // Output: Initial counter: 10
Re-assign `var`
Next, we can easily change the value of the counter variable. This works just like let.
1counter = 20;2console.log("Re-assigned counter:", counter); // Output: Re-assigned counter: 20
Re-declare `var`
Now, we can declare counter again using var. JavaScript does not give an error; it just overwrites the old variable. This is the problematic behavior.
1var counter = 30;2console.log("Re-declared counter:", counter); // Output: Re-declared counter: 30
Why `var` Re-declaration is Dangerous
The ability to re-declare var variables without an error means you can accidentally overwrite a variable that was declared much earlier in your code. This can cause unexpected behavior and bugs that are very difficult to find. This is a major reason why let and const were introduced and why var is now largely avoided.
Summary of Re-declaration and Re-assignment Rules
Summary of Re-declaration and Re-assignment Rules
| Keyword | Can be Re-declared? | Can be Re-assigned? | When to Use |
|---|---|---|---|
| let | No (SyntaxError) | Yes | For variables whose value will change (e.g., counters, user input). |
| const | No (SyntaxError) | No (TypeError) | For variables whose value should remain fixed (e.g., configuration settings, mathematical constants). |
| var | Yes | Yes | Avoid in modern JavaScript. Used in older codebases. |
Test Your Knowledge
Test Your Knowledge
Which keyword allows re-assignment but prevents re-declaration in the same scope?
What will happen if you run this code? const x = 10; x = 20;
Which statement about var is true?
What is the primary benefit of let and const disallowing re-declaration?
Quick Reference
Quick Reference
- 1Declaration — creating a variable for the first time using
let,const, orvar. - 2Assignment — giving a value to a variable, whether initial or later.
- 3Re-declaration — trying to declare a variable with the same name again.
- 4Re-assignment — changing the value of an already declared variable.
- 5
let— allows re-assignment (x = 20;) but forbids re-declaration (let x = 20;). - 6
const— forbids both re-assignment (x = 20;) and re-declaration (const x = 20;) for primitive values. - 7
constobjects/arrays — you cannot re-assign the variable, but you can change the object's properties or array's elements. - 8
var— allows both re-assignment and re-declaration, which can lead to bugs. - 9Prefer
letandconst— always use these keywords for new code to avoid commonvarpitfalls. - 10Errors are good —
SyntaxErrorforlet/constre-declaration, andTypeErrorforconstre-assignment, help you find mistakes.
Variable Scope
Understand how let, const, and var behave differently in terms of where they can be accessed in your code.
Data Types
Explore the different kinds of values variables can hold, like numbers, strings, booleans, and objects.
Hoisting
Learn about JavaScript's 'hoisting' behavior and how it affects var, let, and const declarations.
Strict Mode
Discover how JavaScript's strict mode can help you write cleaner code and catch more errors.
You now understand Re-declaration and Re-assignment!
You have learned the critical differences in how let, const, and var handle changing variable values and re-declaring them. This knowledge is fundamental for writing robust, error-free JavaScript applications. Keep practicing to solidify these concepts!
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.