Assignment Operators


JavaScript Assignment Operators are symbols used to assign values to variables. They are a fundamental concept in JavaScript, allowing for the dynamic storage and manipulation of data within your scripts. Understanding these operators is crucial for writing efficient and readable code.

Simple Assignment (=)

The simple assignment operator (=) is the most fundamental assignment operator. It assigns the value of its right-hand operand to its left-hand operand.

Example 1: Assigning a Number

// Declare a variable named 'age' and assign it the value 25.
let age = 25;

console.log(age); // Output: 25

Explanation

In this example, the variable age is assigned the numerical value of 25. The = operator takes the value on the right and stores it in the variable on the left.


Example 2: Assigning a String

// Declare a variable named 'greeting' and assign it a string value.
let greeting = "Hello, JavaScript!";

console.log(greeting); // Output: Hello, JavaScript!

Explanation

Here, the variable greeting is assigned the string "Hello, JavaScript!". The assignment operator works with various data types, including strings.


Example 3: Reassigning a Variable

// Declare a variable 'level' and initialize it.
let level = 1;
console.log("Initial level:", level); // Output: Initial level: 1

// Reassign the value of 'level'.
level = 2;
console.log("Updated level:", level); // Output: Updated level: 2

Explanation

This example demonstrates that a variable's value can be updated. The variable level is first assigned 1 and then reassigned the value of 2.

Addition Assignment (+=)

The addition assignment operator (+=) adds the value of the right operand to a variable and assigns the result to the variable. This is a shorthand for variable = variable + value.

Example 1: Adding Numbers

// Initialize 'score' with a value of 10.
let score = 10;

// Add 5 to 'score'.
score += 5; // Equivalent to score = score + 5;

console.log(score); // Output: 15

Explanation

The += operator adds 5 to the current value of score (10) and then updates score with the new value (15).


Example 2: Concatenating Strings

// Initialize 'message' with a string.
let message = "Learning JavaScript is ";

// Concatenate another string to 'message'.
message += "fun!";

console.log(message); // Output: Learning JavaScript is fun!

Explanation

When used with strings, the += operator performs concatenation, joining the strings together.


Example 3: Building a Shopping List

// Start with an initial item.
let shoppingList = "Milk";

// Add more items to the list.
shoppingList += ", Bread";
shoppingList += ", Eggs";

console.log(shoppingList); // Output: Milk, Bread, Eggs

Explanation

This demonstrates how += can be used to incrementally build a string from multiple parts.

Subtraction Assignment (-=)

The subtraction assignment operator (-=) subtracts the value of the right operand from a variable and assigns the result to the variable. It's a concise way of writing variable = variable - value.

Example 1: Decrementing a Value

// Set an initial health value.
let health = 100;

// Subtract 20 from 'health'.
health -= 20; // Same as health = health - 20;

console.log(health); // Output: 80

Explanation

The -= operator subtracts 20 from health's original value of 100, resulting in 80.


Example 2: Reducing Inventory

// Initial stock of an item.
let inventory = 50;
let itemsSold = 15;

// Update the inventory after sales.
inventory -= itemsSold;

console.log("Remaining inventory:", inventory); // Output: Remaining inventory: 35

Explanation

Here, the number of itemsSold is subtracted from the inventory, providing the updated stock count.


Example 3: Adjusting Temperature

// Starting temperature in Celsius.
let temperature = 25;

// A cold front arrives, dropping the temperature.
temperature -= 7;

console.log("New temperature:", temperature); // Output: New temperature: 18

Explanation

This shows a practical application of decreasing a numerical value representing a real-world measurement.

Multiplication Assignment (*=)

The multiplication assignment operator (*=) multiplies a variable by the value of the right operand and assigns the result to the variable. This is a shorthand for variable = variable * value.

Example 1: Doubling a Value

// A variable 'points' with an initial value.
let points = 10;

// Double the points.
points *= 2; // Equivalent to points = points * 2;

console.log(points); // Output: 20

Explanation

The *= operator multiplies the current value of points by 2 and updates points with the result.


Example 2: Calculating Area

// Start with the length of a square.
let sideLength = 5;
let area = sideLength;

// Calculate the area by multiplying the side by itself.
area *= sideLength;

console.log("Area of the square:", area); // Output: Area of the square: 25

Explanation

This example calculates the area of a square by multiplying the sideLength by itself and storing it in the area variable.


Example 3: Applying a Multiplier

// Initial game score.
let gameScore = 100;
const scoreMultiplier = 1.5;

// Apply the score multiplier.
gameScore *= scoreMultiplier;

console.log("Final score:", gameScore); // Output: Final score: 150

Explanation

The *= operator is used to apply a scoreMultiplier to the gameScore, updating it with the new, higher value.

Division Assignment (/=)

The division assignment operator (/=) divides a variable by the value of the right operand and assigns the result to the variable. This is a shorthand for variable = variable / value.

Example 1: Halving a Value

// A variable 'distance' with an initial value.
let distance = 100;

// Halve the distance.
distance /= 2; // Same as distance = distance / 2;

console.log(distance); // Output: 50

Explanation

The /= operator divides the current value of distance by 2 and assigns the result back to distance.


Example 2: Splitting a Bill

// Total bill amount.
let totalBill = 120;
let numberOfPeople = 4;

// Calculate the share per person.
totalBill /= numberOfPeople;

console.log("Each person pays:", totalBill); // Output: Each person pays: 30

Explanation

The totalBill is divided by the numberOfPeople to determine the amount each person needs to pay.


Example 3: Converting Units

// Length in centimeters.
let lengthInCm = 1000;

// Convert centimeters to meters.
lengthInCm /= 100;

console.log("Length in meters:", lengthInCm); // Output: Length in meters: 10

Explanation

This shows how /= can be used for unit conversion, in this case, from centimeters to meters.

Remainder Assignment (%=)

The remainder assignment operator (%=) divides a variable by the value of the right operand and assigns the remainder of the division to the variable. This is a shorthand for variable = variable % value.

Example 1: Finding the Remainder

// A variable with an initial value.
let number = 10;

// Get the remainder when divided by 3.
number %= 3; // Equivalent to number = 10 % 3;

console.log(number); // Output: 1

Explanation

The %= operator calculates the remainder of 10 divided by 3, which is 1, and updates number to this value.


Example 2: Checking for Even or Odd

// A number to check.
let value = 7;
let remainder = value;

// Get the remainder when divided by 2.
remainder %= 2;

if (remainder === 0) {
  console.log("The number is even.");
} else {
  console.log("The number is odd."); // This will be executed
}

Explanation

A common use for the remainder operator is to determine if a number is even or odd. If a number divided by 2 has a remainder of 0, it's even; otherwise, it's odd.


Example 3: Cycling Through an Array

// An array of colors.
const colors = ["red", "green", "blue"];
let currentIndex = 5;

// Keep the index within the bounds of the array.
currentIndex %= colors.length; // 5 % 3 is 2

console.log(colors[currentIndex]); // Output: blue

Explanation

The %= operator is useful for creating cyclical behavior. It ensures that currentIndex wraps around to stay within the valid range of array indices.

Exponentiation Assignment (**=) (ES2016+)

The exponentiation assignment operator (**=), introduced in ES2016, raises a variable to the power of the right operand and assigns the result to the variable. This is a shorthand for variable = variable ** value.

Example 1: Squaring a Number

// A variable with an initial value.
let base = 3;

// Square the base.
base **= 2; // Same as base = 3 ** 2;

console.log(base); // Output: 9

Explanation

The **= operator raises the value of base (3) to the power of 2, resulting in 9.


Example 2: Cubing a Number

// A variable with an initial value.
let side = 4;

// Calculate the cube of the side.
side **= 3;

console.log("Volume of the cube:", side); // Output: Volume of the cube: 64

Explanation

This example calculates the volume of a cube by raising the side length to the power of 3.


Example 3: Exponential Growth

// Initial population.
let population = 100;
let growthPeriods = 3;

// Simulate population growth over several periods.
population **= growthPeriods;

console.log("Final population:", population); // Output: Final population: 1000000

Explanation

The **= operator can model exponential growth by repeatedly multiplying the population by itself for a number of growthPeriods.