Now that you’ve mastered JavaScript data types from our previous tutorial, it’s time to learn how to manipulate these data types using operators. In this comprehensive guide, we’ll explore all the essential JavaScript operators that will help you perform calculations and implement logic in your programs.
1. Understanding JavaScript Operators
Before we start specific operators, let’s understand what operators really are in JavaScript. An operator is a special symbol that tells JavaScript to perform a specific mathematical, relational, or logical operation and produce a result.
Think of operators like the buttons on a calculator:
- When you press ‘+’, you’re using an operator to add numbers
- When you press ‘=’, you’re using an operator to assign a result
- When you press ‘%’, you’re using an operator to find a remainder
2. Arithmetic Operators: Making Calculations
Basic Arithmetic
// Basic math operations
let num1 = 10;
let num2 = 3;
let sum = num1 + num2; // Addition: 13
let difference = num1 - num2; // Subtraction: 7
let product = num1 * num2; // Multiplication: 30
let quotient = num1 / num2; // Division: 3.333...
let remainder = num1 % num2; // Modulus: 1
let power = num1 ** num2; // Exponentiation: 1000
Let’s break down each arithmetic operator:
- Addition (+)
- Adds two numbers together
- Also used for string concatenation
- Example:
5 + 3
equals8
- Subtraction (-)
- Subtracts the right number from the left
- Example:
5 - 3
equals2
- Multiplication (*)
- Multiplies two numbers
- Example:
5 * 3
equals15
- Division (/)
- Divides the left number by the right number
- Always returns a floating-point number
- Example:
15 / 3
equals5
- Modulus (%)
- Returns the remainder after division
- Very useful for determining if a number is even or odd
- Example:
7 % 3
equals1
- Exponentiation (**)
- Raises the left number to the power of the right number
- Example:
2 ** 3
equals8
Real-World Calculation Example
// Calculating total cost with tax and discount
let productPrice = 79.99;
let quantity = 2;
let taxRate = 0.08; // 8% tax
let discountRate = 0.15; // 15% discount
// Step by step calculation
let subtotal = productPrice * quantity; // 159.98
let discount = subtotal * discountRate; // 23.997
let priceAfterDiscount = subtotal - discount; // 135.983
let tax = priceAfterDiscount * taxRate; // 10.87864
let finalPrice = priceAfterDiscount + tax; // 146.86164
let roundedPrice = Math.round(finalPrice * 100) / 100; // 146.86
In this example, we:
- Calculate the subtotal by multiplying price and quantity
- Calculate the discount amount
- Subtract the discount from subtotal
- Calculate tax on the discounted price
- Add tax to get the final price
- Round to 2 decimal places using Math.round()
3. Assignment Operators: Storing Values
Assignment operators are used to assign values to variables. They can combine assignment with arithmetic operations.
let score = 10; // Basic assignment
// Compound assignment operators
score += 5; // score = score + 5 (now 15)
score -= 3; // score = score - 3 (now 12)
score *= 2; // score = score * 2 (now 24)
score /= 4; // score = score / 4 (now 6)
score %= 4; // score = score % 4 (now 2)
score **= 3; // score = score ** 3 (now 8)
Each compound assignment operator:
- Takes the current value of the variable
- Performs the arithmetic operation
- Assigns the result back to the variable
These operators make your code shorter and more readable. Instead of writing score = score + 5
, you can write score += 5
.
4. Comparison Operators: Making Decisions
Comparison operators compare two values and return a boolean result (true or false).
let x = 5;
let y = "5";
let z = 10;
// Equality operators
console.log(x == y); // true (loose equality)
console.log(x === y); // false (strict equality)
console.log(x != z); // true (loose inequality)
console.log(x !== y); // true (strict inequality)
// Relational operators
console.log(x < z); // true
console.log(x > z); // false
console.log(x <= z); // true
console.log(x >= z); // false
Understanding equality operators:
==
(loose equality): Compares values after type conversion===
(strict equality): Compares both values and types- Always prefer
===
unless you have a specific reason to use==
Example of why ===
is important:
let number = 0;
let falsy = "";
console.log(number == falsy); // true (because both are falsy values)
console.log(number === falsy); // false (different types)
5. Logical Operators: Combining Conditions
Logical operators help you combine multiple conditions.
let isLoggedIn = true;
let hasPremium = false;
let isAdmin = true;
// AND operator (&&)
let canAccessPremiumContent = isLoggedIn && hasPremium; // false
// OR operator (||)
let hasAccess = isAdmin || hasPremium; // true
// NOT operator (!)
let isGuest = !isLoggedIn; // false
Understanding logical operators:
- AND (&&)
- Returns true only if both conditions are true
- Often used for permission checking
- Example:
isAdult && hasLicense
for driving eligibility
- OR (||)
- Returns true if at least one condition is true
- Great for providing alternatives
- Example:
isVIP || hasCoupon
for discount eligibility
- NOT (!)
- Reverses a boolean value
- Useful for checking opposite conditions
- Example:
!isExpired
to check if something is still valid
Complex Logical Examples
// User access control system
let age = 25;
let hasSubscription = true;
let isBlocked = false;
// Complex condition
let canAccessContent = (age >= 18 && hasSubscription) && !isBlocked;
// Even more complex with OR
let hasAccess =
(isAdmin) ||
(age >= 18 && hasSubscription && !isBlocked);
6. Unary Operators: Single Value Operations
Unary operators work with just one value. The most common ones are increment (++) and decrement (–).
let counter = 5;
// Postfix increment/decrement
let post = counter++; // post = 5, counter = 6
let post2 = counter--; // post2 = 6, counter = 5
// Prefix increment/decrement
let pre = ++counter; // pre = 6, counter = 6
let pre2 = --counter; // pre2 = 5, counter = 5
// Unary plus and minus
let str = "123";
let num = +str; // Converts to number 123
let negative = -num; // Makes it -123
Key differences:
- Prefix (++x): Increments first, then returns value
- Postfix (x++): Returns value first, then increments
- Unary plus (+): Converts to number
- Unary minus (-): Negates a number
7. Conditional (Ternary) Operator: Quick Decisions
The ternary operator is a shorthand way to write simple if-else statements.
// Syntax: condition ? valueIfTrue : valueIfFalse
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
// Equivalent to:
let status2;
if (age >= 18) {
status2 = "Adult";
} else {
status2 = "Minor";
}
When to use the ternary operator:
- For simple conditions with two outcomes
- When assigning a value based on a condition
- To make code more concise
8. Real-World Examples
Example 1: Shopping Cart Total Calculation
function calculateCartTotal(items, isVIPMember) {
let subtotal = 0;
// Calculate subtotal
items.forEach(item => {
subtotal += item.price * item.quantity;
});
// Apply discount based on membership
let discount = isVIPMember ? 0.2 : (subtotal >= 100 ? 0.1 : 0);
let discountAmount = subtotal * discount;
// Calculate tax (assuming 8% tax rate)
let taxAmount = (subtotal - discountAmount) * 0.08;
// Calculate final total
let total = subtotal - discountAmount + taxAmount;
return Math.round(total * 100) / 100;
}
// Example usage
let cartItems = [
{ price: 29.99, quantity: 2 },
{ price: 49.99, quantity: 1 }
];
let total = calculateCartTotal(cartItems, true);
Example 2: Form Validation
function validateUserInput(username, password, email) {
// Check username requirements
let isUsernameValid = username.length >= 3 && username.length <= 20;
// Check password strength
let hasUpperCase = /[A-Z]/.test(password);
let hasNumber = /[0-9]/.test(password);
let isPasswordValid = password.length >= 8 && hasUpperCase && hasNumber;
// Check email format (simple check)
let isEmailValid = email.includes('@') && email.includes('.');
// Combine all validations
return isUsernameValid && isPasswordValid && isEmailValid;
}
// Example usage
let isValid = validateUserInput("john_doe", "Password123", "john@email.com");
Practice Exercises for You
- Create a function that calculates the body mass index (BMI) using arithmetic operators
- Write a function that checks if a number is even or odd using the modulus operator
- Create a password strength checker using logical operators
- Implement a simple tax calculator with different tax brackets using comparison operators
Conclusion
Understanding JavaScript operators is crucial for writing effective code. They’re the building blocks that allow you to perform calculations, make decisions, and control program flow. Practice using these operators in different combinations, and you’ll become more comfortable with them over time.
In our next tutorial, we’ll learn how to Write Clean JavaScript Comments in Your Code.