Operators are symbols that perform operations on values and variables. They're the verbs of programming—they let you do math, compare values, make logical decisions, and modify data. From simple addition to complex logical expressions, operators are fundamental to writing functional code. Let's master them all!
What Are Operators?
An operator is a symbol that tells JavaScript to perform a specific operation. Operators work on operands (the values they operate on).
// In this expression:
5 + 3
// "+" is the operator
// "5" and "3" are the operands
// The result is 8
let x = 10;
// "=" is the assignment operator
// "x" is the left operand
// "10" is the right operandJavaScript has several categories of operators:
- Arithmetic operators (math)
- Assignment operators (storing values)
- Comparison operators (comparing values)
- Logical operators (combining conditions)
- String operators (working with text)
- Unary operators (working with one operand)
- Ternary operator (conditional expressions)
Arithmetic Operators
Arithmetic operators perform mathematical calculations on numbers.
Basic Arithmetic
// Addition (+)
console.log(10 + 5); // 15
console.log(2.5 + 3.7); // 6.2
// Subtraction (-)
console.log(10 - 5); // 5
console.log(3.7 - 2.5); // 1.2
// Multiplication (*)
console.log(10 * 5); // 50
console.log(2.5 * 4); // 10
// Division (/)
console.log(10 / 5); // 2
console.log(10 / 3); // 3.3333333333333335
// Modulus (%) - remainder after division
console.log(10 % 3); // 1 (10 divided by 3 is 3 remainder 1)
console.log(15 % 4); // 3 (15 divided by 4 is 3 remainder 3)
console.log(20 % 5); // 0 (20 divided by 5 is 4 remainder 0)
// Exponentiation (**) - power
console.log(2 ** 3); // 8 (2 to the power of 3)
console.log(5 ** 2); // 25 (5 squared)
console.log(10 ** 0); // 1 (anything to power 0 is 1)Practical Uses of Modulus (%)
// Check if number is even or odd
let num = 17;
if (num % 2 === 0) {
console.log("Even");
} else {
console.log("Odd"); // This executes
}
// Check if number is divisible by another
let score = 150;
if (score % 10 === 0) {
console.log("Score is divisible by 10"); // Executes
}
// Cycle through values (wrapping)
let items = 5;
let currentIndex = 7;
let actualIndex = currentIndex % items;
console.log(actualIndex); // 2 (7 % 5 = 2)
// Get last digit of a number
let number = 12345;
let lastDigit = number % 10;
console.log(lastDigit); // 5Operator Precedence (Order of Operations)
// JavaScript follows PEMDAS/BODMAS rules
// Parentheses/Brackets, Exponents, Multiplication/Division, Addition/Subtraction
console.log(2 + 3 * 4); // 14 (not 20) - multiply first
console.log((2 + 3) * 4); // 20 - parentheses first
console.log(10 - 2 + 3); // 11 (left to right for same precedence)
console.log(10 / 2 * 3); // 15 (left to right)
console.log(2 ** 3 ** 2); // 512 (exponents are right to left!)
// This is 2 ** (3 ** 2) = 2 ** 9 = 512
// Not (2 ** 3) ** 2 = 8 ** 2 = 64
// Complex expression
let result = 10 + 2 * 5 - 3 ** 2;
console.log(result); // 11
// Step 1: 3 ** 2 = 9
// Step 2: 2 * 5 = 10
// Step 3: 10 + 10 = 20
// Step 4: 20 - 9 = 11📐 Math Tip:
When in doubt, use parentheses to make your intention clear. Code like (price * quantity) + tax is easier to understand than price * quantity + tax even though they do the same thing.
Assignment Operators
Assignment operators assign values to variables.
Basic Assignment (=)
// Simple assignment
let x = 10;
let name = "John";
let isActive = true;
// Chained assignment (not recommended for clarity)
let a, b, c;
a = b = c = 5;
console.log(a, b, c); // 5 5 5Compound Assignment Operators
let x = 10;
// Addition assignment (+=)
x += 5; // Same as: x = x + 5
console.log(x); // 15
// Subtraction assignment (-=)
x -= 3; // Same as: x = x - 3
console.log(x); // 12
// Multiplication assignment (*=)
x *= 2; // Same as: x = x * 2
console.log(x); // 24
// Division assignment (/=)
x /= 4; // Same as: x = x / 4
console.log(x); // 6
// Modulus assignment (%=)
x %= 4; // Same as: x = x % 4
console.log(x); // 2
// Exponentiation assignment (**=)
x **= 3; // Same as: x = x ** 3
console.log(x); // 8Practical Examples
// Increment score
let score = 0;
score += 10; // Add 10 points
score += 5; // Add 5 more points
console.log(score); // 15
// Apply discount
let price = 100;
price *= 0.9; // 10% discount (multiply by 0.9)
console.log(price); // 90
// Accumulate totals
let total = 0;
total += 50; // First purchase
total += 30; // Second purchase
total += 20; // Third purchase
console.log(total); // 100
// Update inventory
let inventory = 100;
inventory -= 15; // Sold 15 items
console.log(inventory); // 85Increment and Decrement Operators
Special operators to add or subtract 1 from a variable.
Increment (++)
let count = 0;
// Post-increment (use current value, then increment)
console.log(count++); // 0 (uses 0, then increments)
console.log(count); // 1
// Pre-increment (increment, then use new value)
count = 0;
console.log(++count); // 1 (increments, then uses 1)
console.log(count); // 1
// Practical example
let likes = 10;
likes++; // Same as: likes = likes + 1
console.log(likes); // 11Decrement (--)
let count = 10;
// Post-decrement
console.log(count--); // 10 (uses 10, then decrements)
console.log(count); // 9
// Pre-decrement
count = 10;
console.log(--count); // 9 (decrements, then uses 9)
console.log(count); // 9
// Practical example
let itemsLeft = 5;
itemsLeft--; // Same as: itemsLeft = itemsLeft - 1
console.log(itemsLeft); // 4When to Use Which
// For standalone statements, both work the same
let x = 5;
x++; // x is now 6
++x; // x is now 7
// Difference matters in expressions
let a = 5;
let b = a++; // b = 5, a = 6 (use then increment)
let c = 5;
let d = ++c; // d = 6, c = 6 (increment then use)
// Most common: standalone increment/decrement
for (let i = 0; i < 5; i++) { // i++ is clearest
console.log(i);
}Best Practice: Use ++ and -- as standalone statements (on their own line) rather than inside expressions. This makes code clearer and avoids confusion about when the increment happens.
Comparison Operators
Comparison operators compare two values and return a boolean (true or false).
Equality Operators
// Strict equality (===) - checks value AND type
console.log(5 === 5); // true
console.log(5 === "5"); // false (different types)
console.log(true === 1); // false (different types)
// Strict inequality (!==) - opposite of ===
console.log(5 !== 5); // false
console.log(5 !== "5"); // true (different types)
console.log(true !== 1); // true (different types)
// Loose equality (==) - checks value only (with type coercion)
console.log(5 == "5"); // true (string "5" converted to number)
console.log(true == 1); // true (true converted to 1)
console.log(false == 0); // true (false converted to 0)
console.log("" == 0); // true (empty string converted to 0)
// Loose inequality (!=) - opposite of ==
console.log(5 != "5"); // false
console.log(5 != 6); // trueCritical: ALWAYS use === and !== instead of == and !=. Loose equality can cause unexpected bugs due to type coercion.
Relational Operators
// Greater than (>)
console.log(10 > 5); // true
console.log(5 > 10); // false
console.log(5 > 5); // false (not greater, equal)
// Less than (<)
console.log(5 < 10); // true
console.log(10 < 5); // false
console.log(5 < 5); // false
// Greater than or equal (>=)
console.log(10 >= 5); // true
console.log(5 >= 5); // true
console.log(3 >= 5); // false
// Less than or equal (<=)
console.log(5 <= 10); // true
console.log(5 <= 5); // true
console.log(10 <= 5); // false
// String comparison (alphabetical)
console.log("a" < "b"); // true
console.log("apple" < "banana"); // true
console.log("Z" < "a"); // true (uppercase before lowercase)Practical Comparisons
// Age verification
let age = 18;
if (age >= 18) {
console.log("Adult");
}
// Grade checking
let score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B"); // This executes
}
// Price comparison
let budget = 1000;
let price = 850;
if (price <= budget) {
console.log("Can afford"); // Executes
}
// String equality (case-sensitive!)
let input = "yes";
if (input === "yes") {
console.log("Confirmed");
}
// Be careful with types
let userAge = "18"; // String from input
if (userAge === 18) {
console.log("Adult"); // Won't execute! Different types
}
if (Number(userAge) === 18) {
console.log("Adult"); // Executes - converted to number
}Logical Operators
Logical operators combine multiple conditions and return boolean values.
AND Operator (&&)
Returns true only if both conditions are true.
// Basic AND
console.log(true && true); // true
console.log(true && false); // false
console.log(false && true); // false
console.log(false && false); // false
// Practical examples
let age = 25;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("Can drive"); // Executes (both true)
}
// Multiple conditions
let score = 85;
let attendance = 95;
let homework = true;
if (score >= 80 && attendance >= 90 && homework) {
console.log("Honor roll"); // Executes (all true)
}
// Range checking
let temperature = 72;
if (temperature >= 60 && temperature <= 80) {
console.log("Comfortable"); // Executes
}OR Operator (||)
Returns true if at least one condition is true.
// Basic OR
console.log(true || true); // true
console.log(true || false); // true
console.log(false || true); // true
console.log(false || false); // false
// Practical examples
let isWeekend = true;
let isHoliday = false;
if (isWeekend || isHoliday) {
console.log("Day off"); // Executes (one is true)
}
// Multiple options
let payment = "credit";
if (payment === "cash" || payment === "credit" || payment === "debit") {
console.log("Payment accepted"); // Executes
}
// Default values
let username = "";
let displayName = username || "Guest";
console.log(displayName); // "Guest" (username is falsy)NOT Operator (!)
Inverts (flips) a boolean value.
// Basic NOT
console.log(!true); // false
console.log(!false); // true
// Double NOT converts to boolean
console.log(!!"hello"); // true
console.log(!!0); // false
// Practical examples
let isLoggedIn = false;
if (!isLoggedIn) {
console.log("Please log in"); // Executes
}
// Checking for empty
let username = "";
if (!username) {
console.log("Username required"); // Executes
}
// Inverting conditions
let hasErrors = true;
if (!hasErrors) {
console.log("Form is valid");
} else {
console.log("Fix errors"); // Executes
}Combining Logical Operators
// AND has higher precedence than OR
let a = true;
let b = false;
let c = true;
console.log(a || b && c); // true
// Same as: a || (b && c)
// (b && c) = false, then (a || false) = true
// Use parentheses for clarity
let age = 25;
let hasLicense = true;
let hasInsurance = false;
let hasCar = true;
// Can drive if: (18+ AND has license) AND (has insurance OR has car)
if ((age >= 18 && hasLicense) && (hasInsurance || hasCar)) {
console.log("Can drive"); // Executes
}
// Complex example: discount eligibility
let isMember = true;
let cartTotal = 150;
let hasCode = false;
if (isMember && (cartTotal >= 100 || hasCode)) {
console.log("Eligible for discount"); // Executes
}Short-Circuit Evaluation
// AND (&&) stops at first falsy value
console.log(false && expensive()); // false (expensive() never runs)
console.log(true && "value"); // "value" (returns second value)
// OR (||) stops at first truthy value
console.log(true || expensive()); // true (expensive() never runs)
console.log(false || "default"); // "default" (returns second value)
// Practical: default values
let userColor = "";
let color = userColor || "blue";
console.log(color); // "blue"
// Practical: conditional execution
let isAdmin = true;
isAdmin && console.log("Admin access granted"); // Executes
// Practical: safe property access
let user = null;
let name = user && user.name; // null (doesn't error)
console.log(name); // nullTernary Operator (Conditional)
The ternary operator is a shorthand for if-elsestatements. It's the only JavaScript operator that takes three operands.
Syntax
// condition ? valueIfTrue : valueIfFalse
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"
// Equivalent if-else
let status2;
if (age >= 18) {
status2 = "Adult";
} else {
status2 = "Minor";
}
console.log(status2); // "Adult"Practical Examples
// Simple assignment
let score = 85;
let grade = score >= 60 ? "Pass" : "Fail";
console.log(grade); // "Pass"
// In template literals
let temp = 30;
let message = `It's ${temp >= 25 ? "hot" : "cool"} today`;
console.log(message); // "It's hot today"
// Function arguments
function greet(name) {
console.log(`Hello, ${name || "Guest"}!`);
}
greet(); // "Hello, Guest!"
greet("John"); // "Hello, John!"
// Return values
function getDiscount(isMember) {
return isMember ? 0.2 : 0.1;
}
console.log(getDiscount(true)); // 0.2
console.log(getDiscount(false)); // 0.1
// Conditional rendering (common in React)
let isLoggedIn = true;
let button = isLoggedIn ? "Logout" : "Login";
console.log(button); // "Logout"Nested Ternary (Use Sparingly)
// Nested ternary for multiple conditions
let score = 85;
let grade = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" :
score >= 60 ? "D" : "F";
console.log(grade); // "B"
// Better: use if-else for complex logic
let grade2;
if (score >= 90) {
grade2 = "A";
} else if (score >= 80) {
grade2 = "B";
} else if (score >= 70) {
grade2 = "C";
} else if (score >= 60) {
grade2 = "D";
} else {
grade2 = "F";
}
console.log(grade2); // "B" (more readable)Readability: Use ternary operators for simple conditions. For complex logic with multiple conditions, use regular if-else statements for better readability.
typeof Operator
The typeof operator returns a string indicating the type of a value.
// Check types
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (JavaScript quirk!)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"
// Practical use: validation
function process(value) {
if (typeof value === "string") {
console.log("Processing string:", value.toUpperCase());
} else if (typeof value === "number") {
console.log("Processing number:", value * 2);
} else {
console.log("Unknown type");
}
}
process("hello"); // Processing string: HELLO
process(42); // Processing number: 84Operator Precedence Table
When multiple operators are used in an expression, precedence determines the order of evaluation.
Precedence (highest to lowest):
- Grouping:
() - Unary:
!,typeof,++,-- - Exponentiation:
** - Multiplication/Division:
*,/,% - Addition/Subtraction:
+,- - Comparison:
<,>,<=,>= - Equality:
===,!==,==,!= - Logical AND:
&& - Logical OR:
|| - Ternary:
? : - Assignment:
=,+=,-=, etc.
// Complex expression
let result = 5 + 3 * 2 > 10 && true;
console.log(result); // true
// Step by step:
// 1. 3 * 2 = 6
// 2. 5 + 6 = 11
// 3. 11 > 10 = true
// 4. true && true = true
// Use parentheses to be clear
let result2 = ((5 + (3 * 2)) > 10) && true;
console.log(result2); // true (same result, clearer intent)Practical Examples
Example 1: Form Validation
function validateForm(username, password, age) {
// Check if all fields are filled
if (!username || !password || !age) {
return "All fields are required";
}
// Username validation
if (username.length < 3 || username.length > 20) {
return "Username must be 3-20 characters";
}
// Password validation
if (password.length < 8) {
return "Password must be at least 8 characters";
}
// Age validation
let ageNum = Number(age);
if (isNaN(ageNum) || ageNum < 13 || ageNum > 120) {
return "Invalid age";
}
return "Valid form!";
}
console.log(validateForm("john", "pass123456", "25"));
// "Valid form!"Example 2: Shopping Cart
function calculateTotal(price, quantity, isMember, hasCode) {
// Base calculation
let subtotal = price * quantity;
// Member discount (10%)
let memberDiscount = isMember ? subtotal * 0.1 : 0;
// Promo code discount (additional 5%)
let codeDiscount = hasCode ? subtotal * 0.05 : 0;
// Total discounts
let totalDiscount = memberDiscount + codeDiscount;
// Apply discounts
let total = subtotal - totalDiscount;
// Free shipping if over $50
let shipping = total >= 50 ? 0 : 5.99;
// Final total
let finalTotal = total + shipping;
return {
subtotal: subtotal.toFixed(2),
discount: totalDiscount.toFixed(2),
shipping: shipping.toFixed(2),
total: finalTotal.toFixed(2)
};
}
console.log(calculateTotal(25, 3, true, true));
// { subtotal: "75.00", discount: "11.25", shipping: "0.00", total: "63.75" }Example 3: Grade Calculator
function calculateGrade(scores) {
// Calculate average
let sum = 0;
for (let i = 0; i < scores.length; i++) {
sum += scores[i];
}
let average = sum / scores.length;
// Determine letter grade
let grade = average >= 90 ? "A" :
average >= 80 ? "B" :
average >= 70 ? "C" :
average >= 60 ? "D" : "F";
// Determine status
let passed = average >= 60;
let honors = average >= 90;
return {
average: average.toFixed(1),
grade: grade,
passed: passed,
honors: honors
};
}
console.log(calculateGrade([85, 92, 78, 95]));
// { average: "87.5", grade: "B", passed: true, honors: false }Operator Playground
Experiment with all types of operators
console.log() to see your output in the console above.Key Takeaways
- Arithmetic operators:
+,-,*,/,%,** - Use
%(modulus) to check divisibility and get remainders - Assignment shortcuts:
+=,-=,*=,/= ++and--add or subtract 1- Always use
===and!==for comparisons - Logical operators:
&&(AND),||(OR),!(NOT) &&returns true only if both conditions are true||returns true if at least one condition is true- Ternary operator:
condition ? true : false - Operator precedence follows PEMDAS; use parentheses for clarity
- Short-circuit evaluation:
&&and||stop early
What's Next?
Congratulations! You've completed the JavaScript Fundamentals section. You now understand variables, data types, strings, type conversion, and all the essential operators. These are the building blocks you'll use in every program you write.
In the next lesson, we'll move into Control Flow and learn about If/Else Statements—how to make your programs make decisions and execute different code based on conditions. This is where your code starts to get really smart!
💪 Practice Challenge:
Before moving on, try creating:
- A calculator function that takes two numbers and an operator (+, -, *, /)
- A function that checks if a number is even or odd using modulus
- A discount calculator that applies different discounts based on purchase amount
- A function that validates if someone can vote (age greater than or equal to 18 AND citizen)
- Use ternary operators to create a message based on temperature (hot/cold/comfortable)
Test Your Understanding
What will this code output?
console.log(10 + 5 * 2);