Lesson 1.3: Operators and Expressions
Duration: 50 minutes
Learning Objectives
By the end of this lesson, you will be able to:
- Use arithmetic operators for mathematical calculations
- Compare values with comparison operators
- Combine conditions with logical operators
- Understand operator precedence
- Write complex expressions
What are Operators?
Operators are symbols that perform operations on values. You have already seen some operators in the previous lessons. Now let's explore them in depth.
// Examples of operators in action
const sum = 5 + 3; // + is an operator
const isEqual = 5 === 5; // === is an operator
const canVote = age >= 18; // >= is an operator
Arithmetic Operators
Arithmetic operators perform mathematical calculations.
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 5 - 3 |
2 |
* |
Multiplication | 5 * 3 |
15 |
/ |
Division | 15 / 3 |
5 |
% |
Modulo (remainder) | 17 % 5 |
2 |
** |
Exponentiation | 2 ** 3 |
8 |
The Modulo Operator
The modulo operator (%) returns the remainder after division:
console.log(17 % 5); // 2 (17 = 5*3 + 2)
console.log(10 % 2); // 0 (10 divides evenly by 2)
console.log(10 % 3); // 1 (10 = 3*3 + 1)
Common uses for modulo:
// Check if a number is even or odd
const num = 7;
const isEven = num % 2 === 0; // false (7 is odd)
// Wrap around values (like clock hours)
let hour = 25;
hour = hour % 24; // 1 (wraps around after 24)
// Every nth item
for (let i = 0; i < 10; i++) {
if (i % 3 === 0) {
console.log(i); // 0, 3, 6, 9
}
}
String Concatenation with +
The + operator also joins strings:
const greeting = 'Hello' + ' ' + 'World';
console.log(greeting); // "Hello World"
// Be careful with mixed types
console.log('5' + 3); // "53" (string concatenation)
console.log(5 + '3'); // "53" (string concatenation)
console.log(5 + 3); // 8 (number addition)
Assignment Operators
Assignment operators store values in variables.
| Operator | Example | Equivalent To |
|---|---|---|
= |
x = 5 |
x = 5 |
+= |
x += 3 |
x = x + 3 |
-= |
x -= 3 |
x = x - 3 |
*= |
x *= 3 |
x = x * 3 |
/= |
x /= 3 |
x = x / 3 |
%= |
x %= 3 |
x = x % 3 |
**= |
x **= 3 |
x = x ** 3 |
let score = 100;
score += 10; // score is now 110
score -= 20; // score is now 90
score *= 2; // score is now 180
score /= 3; // score is now 60
Increment and Decrement
let count = 5;
count++; // count is now 6 (same as count += 1)
count--; // count is now 5 (same as count -= 1)
// Prefix vs Postfix
let a = 5;
console.log(a++); // Prints 5, THEN increments to 6
console.log(a); // Prints 6
let b = 5;
console.log(++b); // Increments to 6, THEN prints 6
console.log(b); // Prints 6
Comparison Operators
Comparison operators compare values and return a boolean (true or false).
| Operator | Name | Example | Result |
|---|---|---|---|
=== |
Strict equal | 5 === 5 |
true |
!== |
Strict not equal | 5 !== 3 |
true |
> |
Greater than | 5 > 3 |
true |
< |
Less than | 5 < 3 |
false |
>= |
Greater than or equal | 5 >= 5 |
true |
<= |
Less than or equal | 5 <= 4 |
false |
Strict vs Loose Equality
// Strict equality (===) - recommended
console.log(5 === 5); // true
console.log(5 === '5'); // false (different types)
console.log(true === 1); // false (different types)
// Loose equality (==) - avoid!
console.log(5 == '5'); // true (converts string to number)
console.log(true == 1); // true (converts boolean to number)
console.log(null == undefined); // true (special case)
Rule: Always use === and !== to avoid unexpected type conversions.
Comparing Strings
Strings are compared alphabetically (by Unicode value):
console.log('apple' < 'banana'); // true (a comes before b)
console.log('Apple' < 'apple'); // true (uppercase comes first)
console.log('10' < '9'); // true (string comparison, not numeric!)
Logical Operators
Logical operators combine multiple conditions.
| Operator | Name | Description |
|---|---|---|
&& |
AND | True if BOTH conditions are true |
|| |
OR | True if AT LEAST ONE condition is true |
! |
NOT | Inverts the boolean value |
AND Operator (&&)
Both conditions must be true:
const age = 25;
const hasLicense = true;
const canDrive = age >= 18 && hasLicense;
console.log(canDrive); // true
// Truth table for AND
console.log(true && true); // true
console.log(true && false); // false
console.log(false && true); // false
console.log(false && false); // false
OR Operator (||)
At least one condition must be true:
const isWeekend = true;
const isHoliday = false;
const dayOff = isWeekend || isHoliday;
console.log(dayOff); // true
// Truth table for OR
console.log(true || true); // true
console.log(true || false); // true
console.log(false || true); // true
console.log(false || false); // false
NOT Operator (!)
Inverts the boolean value:
const isLoggedIn = false;
console.log(!isLoggedIn); // true
console.log(!true); // false
console.log(!false); // true
// Double negation converts to boolean
console.log(!!'hello'); // true
console.log(!!''); // false
console.log(!!0); // false
console.log(!!42); // true
Combining Logical Operators
const age = 25;
const isStudent = true;
const hasDiscount = false;
// Complex condition
const getsReduction = age < 18 || age > 65 || isStudent || hasDiscount;
console.log(getsReduction); // true (because isStudent is true)
// Use parentheses for clarity
const canEnter = age >= 21 && (hasTicket || isVIP);
Short-Circuit Evaluation
Logical operators evaluate left to right and stop early when possible.
AND Short-Circuit
// If first condition is false, second is not evaluated
const result = false && someFunction(); // someFunction() never runs
// Useful pattern: guard clause
const user = null;
const name = user && user.name; // Returns null (doesn't crash)
OR Short-Circuit
// If first condition is true, second is not evaluated
const result = true || someFunction(); // someFunction() never runs
// Useful pattern: default values
const username = inputName || 'Guest'; // "Guest" if inputName is falsy
Nullish Coalescing (??)
The ?? operator returns the right side only if the left side is null or undefined:
const value1 = null ?? 'default'; // "default"
const value2 = undefined ?? 'default'; // "default"
const value3 = 0 ?? 'default'; // 0 (0 is not null/undefined)
const value4 = '' ?? 'default'; // "" (empty string is not null/undefined)
// Compare with OR
const orResult = 0 || 'default'; // "default" (0 is falsy)
const nullishResult = 0 ?? 'default'; // 0 (0 is not null/undefined)
Operator Precedence
Operators are evaluated in a specific order, similar to math.
From highest to lowest precedence:
()- Parentheses (always first)**- Exponentiation*,/,%- Multiplication, division, modulo+,-- Addition, subtraction<,<=,>,>=- Comparison===,!==- Equality&&- Logical AND||- Logical OR=,+=, etc. - Assignment
// Without parentheses
const result1 = 2 + 3 * 4; // 14 (multiplication first)
// With parentheses
const result2 = (2 + 3) * 4; // 20 (parentheses first)
// Complex example
const x = 5;
const y = 10;
const z = 2;
const result = x + y * z > 20 && x < y;
// Evaluates as: (x + (y * z)) > 20 && (x < y)
// = (5 + 20) > 20 && 5 < 10
// = 25 > 20 && true
// = true && true
// = true
Best Practice: Use parentheses to make your intentions clear.
Ternary Operator
A shorthand for simple if/else statements:
// Syntax: condition ? valueIfTrue : valueIfFalse
const age = 20;
const status = age >= 18 ? 'adult' : 'minor';
console.log(status); // "adult"
// Equivalent if/else
let status2;
if (age >= 18) {
status2 = 'adult';
} else {
status2 = 'minor';
}
Practical Examples
// Display message based on condition
const itemCount = 3;
const message = itemCount === 1 ? '1 item' : `${itemCount} items`;
console.log(message); // "3 items"
// Determine greeting based on time
const hour = 14;
const greeting = hour < 12 ? 'Good morning' : 'Good afternoon';
// Nested ternary (use sparingly)
const score = 85;
const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';
Practical Examples
Example 1: Form Validation
const email = 'user@example.com';
const password = 'secret123';
const confirmPassword = 'secret123';
const isEmailValid = email.includes('@') && email.includes('.');
const isPasswordValid = password.length >= 8;
const passwordsMatch = password === confirmPassword;
const canSubmit = isEmailValid && isPasswordValid && passwordsMatch;
console.log(`Can submit: ${canSubmit}`); // true
Example 2: Price Calculator
const price = 100;
const quantity = 3;
const isMember = true;
const couponCode = 'SAVE10';
let total = price * quantity;
// Apply member discount (10%)
if (isMember) {
total *= 0.9;
}
// Apply coupon (additional 10%)
if (couponCode === 'SAVE10') {
total *= 0.9;
}
console.log(`Total: $${total.toFixed(2)}`); // $243.00
Example 3: Grade Calculator
const score = 78;
const passed = score >= 60;
const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : score >= 60 ? 'D' : 'F';
console.log(`Score: ${score}`);
console.log(`Grade: ${grade}`);
console.log(`Passed: ${passed}`);
Exercises
Exercise 1: Calculate Discount
Calculate the final price with these rules:
- Base price: $80
- Quantity: 5
- Discount: 15% if quantity >= 3
Solution
const basePrice = 80;
const quantity = 5;
const discountRate = quantity >= 3 ? 0.15 : 0;
const subtotal = basePrice * quantity;
const discount = subtotal * discountRate;
const finalPrice = subtotal - discount;
console.log(`Subtotal: $${subtotal}`); // $400
console.log(`Discount: $${discount}`); // $60
console.log(`Final Price: $${finalPrice}`); // $340
Exercise 2: Eligibility Checker
Check if a person is eligible for a senior discount:
- Must be 65 or older OR have a senior card
- Must be a member
const age = 70;
const hasSeniorCard = false;
const isMember = true;
Solution
const age = 70;
const hasSeniorCard = false;
const isMember = true;
const isSenior = age >= 65 || hasSeniorCard;
const isEligible = isSenior && isMember;
console.log(`Is Senior: ${isSenior}`); // true
console.log(`Is Eligible: ${isEligible}`); // true
Exercise 3: Time Formatter
Format minutes into hours and minutes. Example: 150 minutes = "2 hours and 30 minutes"
const totalMinutes = 150;
Solution
const totalMinutes = 150;
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
const hourText = hours === 1 ? 'hour' : 'hours';
const minuteText = minutes === 1 ? 'minute' : 'minutes';
console.log(`${hours} ${hourText} and ${minutes} ${minuteText}`);
// Output: "2 hours and 30 minutes"
Key Takeaways
- Arithmetic operators perform math:
+,-,*,/,%,** - Assignment shortcuts save typing:
+=,-=,*=,/= - Always use
===for comparisons, not== - Logical operators combine conditions:
&&(AND),||(OR),!(NOT) - Short-circuit evaluation stops early when result is determined
- Ternary operator is a compact if/else:
condition ? yes : no - Use parentheses to make operator precedence clear
Resources
| Resource | Type | Description |
|---|---|---|
| MDN: Expressions and Operators | Documentation | Complete operators guide |
| MDN: Operator Precedence | Documentation | Precedence table |
| JavaScript.info: Operators | Tutorial | Interactive operators tutorial |
Next Lesson
Now that you can work with values and operators, let's learn how to make decisions in your code.