JavaScript Assignment Operators
Learn how to assign values to variables in JavaScript
📝 What are Assignment Operators?
Assignment operators are used to assign values to JavaScript variables. The most basic assignment operator is the equal sign (=).
// Basic assignment
let name = "John";
let age = 25;
let isStudent = true;
Output:
name = "John"
age = 25
isStudent = true
Types of Assignment Operators
Basic Assignment
Assigns a value to a variable
let x = 10;
Addition Assignment
Adds and assigns the result
x += 5; // x = x + 5
Subtraction Assignment
Subtracts and assigns the result
x -= 3; // x = x - 3
Multiplication Assignment
Multiplies and assigns the result
x *= 2; // x = x * 2
🔹 Basic Assignment (=)
The equal sign (=) assigns the value on the right to the variable on the left:
// Assigning different data types
let message = "Hello World";
let number = 42;
let isActive = false;
let fruits = ["apple", "banana", "orange"];
console.log(message); // "Hello World"
console.log(number); // 42
console.log(isActive); // false
console.log(fruits); // ["apple", "banana", "orange"]
Console Output:
Hello World
42
false
["apple", "banana", "orange"]
🔹 Addition Assignment (+=)
The += operator adds the right operand to the left operand and assigns the result:
// With numbers
let score = 10;
score += 5; // Same as: score = score + 5
console.log(score); // 15
// With strings (concatenation)
let greeting = "Hello";
greeting += " World"; // Same as: greeting = greeting + " World"
console.log(greeting); // "Hello World"
// With arrays
let numbers = [1, 2];
numbers += [3, 4]; // Converts to string concatenation
console.log(numbers); // "1,23,4"
Console Output:
15
Hello World
1,23,4
🔹 Arithmetic Assignment Operators
These operators perform arithmetic operations and assign the result:
let num = 20;
// Subtraction assignment
num -= 5; // num = num - 5
console.log(num); // 15
// Multiplication assignment
num *= 2; // num = num * 2
console.log(num); // 30
// Division assignment
num /= 3; // num = num / 3
console.log(num); // 10
// Modulus assignment
num %= 3; // num = num % 3
console.log(num); // 1
// Exponentiation assignment
num **= 4; // num = num ** 4
console.log(num); // 1
Console Output:
15
30
10
1
1
🔹 Practical Examples
Real-world usage of assignment operators:
// Shopping cart example
let totalPrice = 0;
let itemPrice = 25.99;
let quantity = 3;
// Add items to cart
totalPrice += itemPrice * quantity;
console.log("Cart total: $" + totalPrice); // $77.97
// Apply discount (10% off)
totalPrice *= 0.9;
console.log("After discount: $" + totalPrice.toFixed(2)); // $70.17
// Counter example
let clickCount = 0;
clickCount += 1; // User clicked
clickCount += 1; // User clicked again
console.log("Total clicks: " + clickCount); // 2
Console Output:
Cart total: $77.97
After discount: $70.17
Total clicks: 2