Operators and conditionals
Use arithmetic, comparison and logical operators to make decisions in code.
- Read and use arithmetic, comparison and logical operators
- Choose === over == and explain why
- Write if/else branches and ternaries
- Predict truthy and falsy behaviour
In plain English
Operators are symbols that do work on values: arithmetic operators like +, -, * and / do maths. Comparison operators like === ask a yes-or-no question and produce a boolean (true or false); the strict === checks that both the value and its type match, while the loose == converts types first, which is why "5" == 5 is true but "5" === 5 is false. Logical operators combine conditions, where && means AND, || means OR and ! means NOT. An if/else statement runs one block of code when a condition is true and another when it is false, and a ternary (? :) is a short way to pick between two values.
Step by step
- 1Write an expression using arithmetic operators and log the result.
- 2Compare two values with === and check the boolean it returns.
- 3Combine conditions with &&, || and !.
- 4Branch with if/else, then rewrite the same choice as a ternary.
- 5Test which values JavaScript treats as falsy.
const price = 20;
const taxRate = 0.1;
const total = price + price * taxRate;
const isBigSpender = total >= 25;
const isMember = true;
if (isBigSpender && isMember) {
console.log("10% member discount applied");
} else {
console.log("No extra discount");
}
const emptyName = "";
const fallback = emptyName || "Guest";
const label = total > 25 ? "Big total" : "Budget total";
console.log(label, fallback);Common mistakes
- Using a single = when you meant to compare, because = assigns a value and does not check equality.
- Relying on == and being surprised when "5" == 5 comes out true.
- Forgetting that 0, "", null, undefined and NaN are all falsy values.
- Writing a hard-to-read ternary when a plain if/else would be clearer.
Price with a discount
Write a function totalWithTax(price, isMember) that adds 10% tax, then applies a 5% member discount only when isMember is true. Return the final amount rounded to 2 decimals.
function totalWithTax(price, isMember) {
}Which comparison is true in JavaScript?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.