javascript

Variable Assignment

Learn about variable assignment in JavaScript. Discover how the `=` operator stores values in variables, the difference between initialization and reassignment, and how to use `let` and `const` effectively.

10 min read 8 sections Tutorial
Share

In JavaScript, **variable assignment** is how you give a value to a variable. It's like putting an item into a named box. You use the equals sign (`=`) to tell JavaScript to store a value inside a variable. Understanding assignment is super important because it's how your programs remember information. Every time you update a score, change a user's name, or store a calculation, you are using variable assignment.

Variable Assignment

Variable Assignment

A variable is like a named container for data. Assignment is the action of putting data into that container. You use the single equals sign (=) to perform this action.

When you assign a value, JavaScript first looks at the right side of the = sign. It figures out what that value is. Then, it takes that value and places it into the variable name on the left side of the = sign.

This process is fundamental to how programs work. It allows your code to store information, update it, and use it later.

What is Variable Assignment?

Variable assignment is the process of storing a value into a variable using the assignment operator (=). It gives a variable its initial value or updates its existing value.

The `=` Operator

The single equals sign is the assignment operator. It tells JavaScript to put the value on the right into the variable on the left.

Initialization

This is the very first time you give a value to a variable when you declare it with let or const.

Reassignment

Changing the value of an existing let variable to something new after its initial setup.

const Rules

Variables declared with const must be assigned a value immediately and cannot be reassigned later.

Assigning Values to Variables

Getting Started

Assigning Values to Variables

To assign a value, you first declare a variable using let or const. Then, you use the assignment operator (=) followed by the value you want to store. This is called initialization when it's the first time.

If you use let, you can change the value later. This is called reassignment. With const, you can only assign a value once, when you declare it.

javascript
1// Declare a variable 'userName' and assign it the string value 'Alice'
2let userName = 'Alice';
3console.log(userName); // Output: Alice
4
5// Reassign a new value to 'userName' (only works with let)
6userName = 'Bob';
7console.log(userName); // Output: Bob
8
9// Declare a constant 'MAX_SCORE' and assign it the number 1000
10const MAX_SCORE = 1000;
11console.log(MAX_SCORE); // Output: 1000
12
13// Try to reassign a const variable (this will cause an error)
14// MAX_SCORE = 1200; // ❌ TypeError: Assignment to constant variable.

Assignment vs. Equality

Be careful not to confuse the assignment operator (=) with the equality operator (== or ===).

  • = assigns a value: x = 10; (x becomes 10)
  • == or === checks if values are equal: x == 10; (is x equal to 10?)

How Assignment Works Internally

How Assignment Works Internally

When JavaScript sees an assignment, it performs a few steps. First, it looks at the value on the right side of the = sign. This value is evaluated or computed.

Then, JavaScript finds the memory location reserved for the variable on the left side. It copies the evaluated value into that memory location. For simple values like numbers and strings, a direct copy is made. For complex values like objects and arrays, JavaScript copies a reference, which is like a pointer to where the actual data lives.

javascript
1// Assigning a number (primitive value)
2let num1 = 10; // num1 gets the value 10
3let num2 = num1; // num2 gets a COPY of num1's value (which is 10)
4
5console.log(num1); // 10
6console.log(num2); // 10
7
8// Changing num1 does NOT change num2 because num2 has its own copy
9num1 = 20;
10console.log(num1); // 20
11console.log(num2); // 10 (still 10)
12
13// Assigning an object (non-primitive value)
14let obj1 = { score: 100 }; // obj1 points to an object in memory
15let obj2 = obj1; // obj2 now points to the SAME object as obj1
16
17console.log(obj1.score); // 100
18console.log(obj2.score); // 100
19
20// Changing a property through obj1 ALSO changes it for obj2
21// because they both point to the same object
22obj1.score = 200;
23console.log(obj1.score); // 200
24console.log(obj2.score); // 200 (changed!)
✗ BadWrong — const re-assignment
const gameName; // ❌ Missing value
gameName = 'Adventure'; // ❌ Cannot reassign const
console.log(gameName);
✓ GoodCorrect — const initialization
const gameName = 'Adventure'; // ✅ Assign value immediately
console.log(gameName); // Output: Adventure
// A const variable cannot be changed later
// gameName = 'Quest'; // This would cause an error

Initialization vs. Reassignment

Initialization vs. Reassignment

There are two main ways to assign a value to a variable. Initialization is when you give a variable its very first value at the same time you declare it. For example, let count = 0;.

Reassignment is when you change the value of an already existing variable. This only works for variables declared with let. For example, if count was 0, you could later say count = 10;.

Reassignment with let
// Initialization
let playerLives = 3;
console.log('Lives:', playerLives); // Lives: 3
// Reassignment
playerLives = 2; // Player lost a life
console.log('Lives:', playerLives); // Lives: 2
// Another reassignment
playerLives = playerLives + 1; // Player got a bonus life
console.log('Lives:', playerLives); // Lives: 3
VS
Initialization with const
// Initialization (required)
const GAME_TITLE = 'Space Invaders';
console.log('Game:', GAME_TITLE); // Game: Space Invaders
// Trying to reassign a const variable will fail
// GAME_TITLE = 'Galactic Defender'; // ❌ TypeError
// const variables are good for fixed settings
const MAX_ATTEMPTS = 5;
console.log('Max attempts:', MAX_ATTEMPTS); // Max attempts: 5

Choose wisely: let or const?

If you know a variable's value will never change after its first assignment, use const. If the value might change, use let. This makes your code clearer and helps prevent mistakes.

Practical Uses of Assignment in Programs

Practical Uses of Assignment in Programs

Variable assignment is used everywhere in real-world programs. It's how you keep track of changing data, like a user's score in a game, the items in a shopping cart, or the current time.

By assigning and reassigning values, your program can respond to events, perform calculations, and update what the user sees. It's the core mechanism for managing state, which means the current data your program is working with.

1

Set an initial score

Start a game with a player's score at zero using let for reassignment.

javascript
1let playerScore = 0;
2console.log('Game started. Score:', playerScore);
2

Update score after an event

When the player collects a coin, reassign playerScore to add points.

javascript
1const COIN_VALUE = 10;
2playerScore = playerScore + COIN_VALUE; // Add 10 points
3console.log('Collected coin! Score:', playerScore);
3

Apply a bonus or penalty

After a special event, you might add a large bonus or subtract points. Reassign the variable again.

javascript
1const BONUS_ROUND_POINTS = 50;
2playerScore = playerScore + BONUS_ROUND_POINTS; // Big bonus!
3console.log('Bonus round complete! Score:', playerScore);
4

Calculate a total

Use assignment to store the result of a calculation into a new variable.

javascript
1let itemPrice = 25;
2let quantity = 3;
3let totalCost = itemPrice * quantity; // Calculate and assign
4console.log('Total cost:', totalCost);

Avoid accidental global assignment

If you assign a value to a variable name without first declaring it with let or const (or var), JavaScript might create a global variable. This can lead to unexpected behavior and bugs that are hard to find.

Always use let or const to declare your variables before assigning them values.

Assignment Operators and Rules

Assignment Operators and Rules

OperatorExampleMeaningResult
=`x = 5`Assigns value`x` is `5`
+=`x += 3`Adds and assignsSame as `x = x + 3`
-=`x -= 2`Subtracts and assignsSame as `x = x - 2`
*=`x *= 4`Multiplies and assignsSame as `x = x * 4`
/=`x /= 2`Divides and assignsSame as `x = x / 2`
%=`x %= 3`Remainder and assignsSame as `x = x % 3`

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which operator is used for variable assignment in JavaScript?

Quick Check

What happens if you try to reassign a const variable?

Quick Check

Given let points = 5; points += 3; console.log(points);, what will be printed to the console?

Quick Check

Consider this code: let a = 10; let b = a; b = 20; console.log(a);. What is the value of a?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Assignment Operator — The single equals sign (=) stores a value in a variable.
  • 2Initialization — The first assignment of a value to a variable when it's declared (e.g., let x = 10;).
  • 3Reassignment — Changing the value of an existing let variable (e.g., x = 20;).
  • 4const Ruleconst variables must be initialized immediately and cannot be reassigned later.
  • 5let for Change — Use let when you expect the variable's value to change during the program's execution.
  • 6const for Fixed — Use const for values that should not change, making your code safer and clearer.
  • 7Value Copying — For primitive values (numbers, strings, booleans), assignment copies the actual value.
  • 8Reference Copying — For non-primitive values (objects, arrays), assignment copies a reference, meaning both variables point to the same data.
  • 9Compound Operators — Operators like +=, -=, *= combine an operation with assignment (e.g., x += 5 is x = x + 5).
  • 10Avoid Globals — Always declare variables with let or const before assigning values to prevent accidental global variables.

Data Types

Explore the different kinds of values you can assign: numbers, strings, booleans, objects, and more.

Operators

Learn about other JavaScript operators, including arithmetic, comparison, and logical operators.

Variable Scope

Understand where variables are accessible in your code and how scope affects assignment.

Functions

Discover how assignment is used to pass arguments to functions and store return values.

You've mastered Variable Assignment!

You now understand how to assign values to variables using the = operator, the difference between let and const for assignment, and how values are stored. This knowledge is crucial for writing dynamic and functional JavaScript programs!

Try it in the Javascript Compiler

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

Continue Learning