โก Lesson 4: Operators & Expressions
Learn how to perform calculations, make comparisons, and combine logic โ the tools that make your programs make decisions.
๐ฏ Learning Objectives
By the end of this lesson, you will be able to:
- Use arithmetic operators for math calculations
- Apply assignment operators including shorthand (
+=,-=, etc.) - Compare values with
==,===,!=,!==,<,> - Explain the critical difference between
==and=== - Combine conditions with logical operators (
&&,||,!) - Understand operator precedence and how expressions evaluate
Estimated Time: 45 minutes
Project: Build a tip calculator using operators
๐ In This Lesson
Introduction
Variables store data, but operators let you do things with that data โ add numbers, compare values, combine conditions, and build expressions. An expression is any piece of code that produces a value: 2 + 3 is an expression that produces 5.
This lesson covers the operators you'll use every day in JavaScript.
Arithmetic Operators
These perform math on numbers, just like a calculator.
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 3 | 13 |
- | Subtraction | 10 - 3 | 7 |
* | Multiplication | 10 * 3 | 30 |
/ | Division | 10 / 3 | 3.333... |
% | Modulo (remainder) | 10 % 3 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
let price = 29.99;
let quantity = 3;
let subtotal = price * quantity;
console.log(`Subtotal: $${subtotal}`); // "Subtotal: $89.97"
// Modulo is great for checking even/odd
let number = 7;
console.log(number % 2); // 1 (odd โ remainder when dividing by 2)
console.log(8 % 2); // 0 (even)
// Increment and Decrement
let count = 5;
count++; // count is now 6 (same as count = count + 1)
count--; // count is now 5 again
๐ก Modulo (%) Use Cases
Modulo gives you the remainder after division. Common uses include checking if a number is even (n % 2 === 0), wrapping around values (like cycling through array indices), and converting total seconds into minutes/seconds.
Assignment Operators
You already know = assigns a value. Shorthand operators combine assignment with an operation.
| Operator | Example | Equivalent To |
|---|---|---|
= | x = 10 | Assign 10 to x |
+= | x += 5 | x = x + 5 |
-= | x -= 3 | x = x - 3 |
*= | x *= 2 | x = x * 2 |
/= | x /= 4 | x = x / 4 |
%= | x %= 3 | x = x % 3 |
**= | x **= 2 | x = x ** 2 |
let score = 100;
score += 25; // score is now 125
score -= 10; // score is now 115
score *= 2; // score is now 230
console.log(score); // 230
Comparison Operators
Comparison operators compare two values and return a boolean (true or false). They're the foundation of decision-making in code.
| Operator | Name | Example | Result |
|---|---|---|---|
=== | Strict equal | 5 === 5 | true |
!== | Strict not equal | 5 !== "5" | true |
== | Loose equal | 5 == "5" | true |
!= | Loose not equal | 5 != "5" | false |
> | Greater than | 10 > 5 | true |
< | Less than | 3 < 7 | true |
>= | Greater or equal | 5 >= 5 | true |
<= | Less or equal | 3 <= 2 | false |
The Critical Difference: === vs. ==
This is one of the most important things to understand in JavaScript.
// === (strict equality) โ checks value AND type
console.log(5 === 5); // true (same value, same type)
console.log(5 === "5"); // false (same value, different type!)
console.log(true === 1); // false (different types)
// == (loose equality) โ converts types before comparing
console.log(5 == "5"); // true (JS converts "5" to 5, then compares)
console.log(true == 1); // true (JS converts true to 1)
console.log(null == undefined); // true (special case)
console.log("" == 0); // true (both are "falsy")
โ Always Use === and !==
Loose equality (==) performs type coercion and produces counterintuitive results. Always use strict equality (===) and strict inequality (!==) unless you have a specific reason not to. This is a universal JavaScript best practice.
// Why == is dangerous โ these are all true!
console.log("" == 0); // true
console.log("0" == 0); // true
console.log("" == "0"); // false (both strings, no coercion)
console.log(false == "0"); // true
console.log(false == ""); // true
console.log(null == undefined); // true
// With ===, the results make sense
console.log("" === 0); // false
console.log("0" === 0); // false
console.log(false === "0"); // false
Logical Operators
Logical operators combine boolean values or expressions. They're how you build complex conditions.
| Operator | Name | Description | Example | Result |
|---|---|---|---|---|
&& | AND | Both must be true | true && true | true |
|| | OR | At least one must be true | false || true | true |
! | NOT | Flips the value | !true | false |
let age = 25;
let hasID = true;
// AND โ both conditions must be true
let canEnter = age >= 21 && hasID;
console.log(canEnter); // true
// OR โ at least one condition must be true
let isWeekend = false;
let isHoliday = true;
let dayOff = isWeekend || isHoliday;
console.log(dayOff); // true
// NOT โ flips the boolean
let isLoggedIn = false;
console.log(!isLoggedIn); // true (NOT false = true)
// Combining them
let isMember = true;
let hasCoupon = false;
let getsDiscount = isMember || hasCoupon;
let canCheckout = getsDiscount && age >= 18;
console.log(`Gets discount: ${getsDiscount}`); // true
console.log(`Can checkout: ${canCheckout}`); // true
Truthy and Falsy Values
JavaScript can treat non-boolean values as true or false in logical contexts. These are called truthy and falsy values.
// Falsy values (these all evaluate to false):
// false, 0, -0, "", null, undefined, NaN
// Everything else is truthy:
// true, any number (except 0), any non-empty string, objects, arrays
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(1)); // true
console.log(Boolean("hello")); // true
console.log(Boolean(42)); // true
console.log(Boolean("0")); // true (non-empty string!)
โ ๏ธ Common Gotcha
"0" (the string containing zero) is truthy because it's a non-empty string. 0 (the number zero) is falsy. This catches many beginners off guard.
String Operators
The + operator does double duty โ it adds numbers and concatenates (joins) strings.
// Concatenation
let first = "Java";
let second = "Script";
let combined = first + second;
console.log(combined); // "JavaScript"
// Concatenation with variables
let greeting = "Hello, " + "World!";
console.log(greeting); // "Hello, World!"
// += works with strings too
let message = "Good";
message += " morning!";
console.log(message); // "Good morning!"
โ Prefer Template Literals
For building strings with variables, template literals (backticks) are cleaner than + concatenation. You learned this in Lesson 3 โ keep using them!
Operator Precedence
When an expression has multiple operators, JavaScript follows a specific order โ just like math class (PEMDAS/BODMAS). Key points:
- Parentheses
()โ evaluated first (always use these to be explicit!) - Exponentiation
** - Multiplication / Division / Modulo
* / % - Addition / Subtraction
+ - - Comparisons
< > <= >= - Equality
=== !== == != - Logical AND
&& - Logical OR
|| - Assignment
= += -= etc.
// Without parentheses โ follows precedence rules
let result = 2 + 3 * 4;
console.log(result); // 14 (not 20! multiplication first)
// With parentheses โ explicit and clear
let result2 = (2 + 3) * 4;
console.log(result2); // 20
// Complex expression
let total = 100 - 20 * 0.1 + 5;
console.log(total); // 103 (20 * 0.1 = 2, then 100 - 2 + 5)
// Clear version with parentheses
let total2 = (100 - (20 * 0.1)) + 5;
console.log(total2); // 103 (same result, but intention is clear)
โ Pro Tip: Use Parentheses Generously
Don't rely on memorizing precedence rules. Use parentheses to make your intentions clear. Future you (and anyone reading your code) will thank you.
Hands-on Exercise
๐๏ธ Exercise: Tip Calculator
Objective: Use arithmetic, assignment, and comparison operators to build a console-based tip calculator.
Instructions:
// Tip Calculator
// TODO: Set up these variables
// const billAmount = 85.50;
// const tipPercentage = 20; // 20%
// const numberOfPeople = 3;
// TODO: Calculate:
// 1. tipAmount (billAmount * tipPercentage / 100)
// 2. totalWithTip (billAmount + tipAmount)
// 3. perPerson (totalWithTip / numberOfPeople)
// TODO: Log the results using template literals
// "Bill: $85.50"
// "Tip (20%): $17.10"
// "Total: $102.60"
// "Per person: $34.20"
// BONUS: Check if the bill is "expensive" (over $100 after tip)
// Log whether it is using a comparison
๐ก Hint
Use .toFixed(2) on numbers to format them to two decimal places: perPerson.toFixed(2) gives you "34.20" instead of 34.2.
โ Solution
const billAmount = 85.50;
const tipPercentage = 20;
const numberOfPeople = 3;
const tipAmount = billAmount * tipPercentage / 100;
const totalWithTip = billAmount + tipAmount;
const perPerson = totalWithTip / numberOfPeople;
console.log(`Bill: $${billAmount.toFixed(2)}`);
console.log(`Tip (${tipPercentage}%): $${tipAmount.toFixed(2)}`);
console.log(`Total: $${totalWithTip.toFixed(2)}`);
console.log(`Per person: $${perPerson.toFixed(2)}`);
// Bonus: Check if expensive
const isExpensive = totalWithTip > 100;
console.log(`Expensive? ${isExpensive}`); // true
๐ฏ Quick Quiz
Question 1: What does 10 % 3 return?
Question 2: What does 5 === "5" return?
Question 3: What is the result of true && false || true?
Summary
๐ Key Takeaways
- Arithmetic operators:
+,-,*,/,%,**for math - Assignment shorthand:
+=,-=,*=,/=for cleaner updates - Always use
===(strict equality) and!==instead of==and!= - Logical operators:
&&(AND),||(OR),!(NOT) combine conditions - Truthy/falsy:
0,"",null,undefined,NaNare falsy; everything else is truthy - Use parentheses to make operator precedence clear and intentional
๐ Additional Resources
- MDN โ Expressions and Operators
- javascript.info โ Basic Operators
- javascript.info โ Comparisons
๐ What's Next?
You've completed Module 1! You now have the fundamentals: variables, data types, and operators. In Module 2, you'll learn to control the flow of your programs with conditionals โ making your code make decisions with if, else, and switch.
๐ Module 1 Complete!
You've finished JavaScript Foundations. You understand variables, data types, and operators. Time to make your code think!