3.5 Relational and Logical Operators
Programs do not only run statements in order. They often need to check whether a condition is true, then choose what to do next. A condition usually produces a Boolean value: true or false.
Relational operators
Relational operators compare two values. The result of a comparison is a Boolean value.
Common JavaScript relational operators:
<: less than>: greater than<=: less than or equal to>=: greater than or equal to===: strictly equal to!==: not strictly equal to
Important: one equals sign = means assignment. Three equals signs === mean strict comparison.
let age = 17;
console.log(age < 18); // true
console.log(age === 18); // false
console.log(age !== 18); // trueage = 17 stores 17 in the variable age. age === 18 checks whether the current value of age equals 18 and has the same type.
Why === matters in JavaScript
JavaScript also has ==, called loose equality. It may convert types before comparing, which can surprise beginners.
console.log(1 == "1"); // true
console.log(1 === "1"); // falseUse === and !== by default. They are more predictable because they compare both value and type.
Logical operators
Logical operators combine multiple conditions. Their result is still a Boolean value.
&&: the whole expression istrueonly when every condition istrue.||: the whole expression istruewhen at least one condition istrue.!: turnstrueintofalse, andfalseintotrue.
let age = 20;
let hasTicket = true;
console.log(age >= 18 && hasTicket); // true
console.log(age < 18 || hasTicket); // true
console.log(!hasTicket); // falseIt helps to read conditions like plain language: age >= 18 && hasTicket means "the age is at least 18, and the person has a ticket."
Combining conditions
When a condition becomes complex, use parentheses or meaningful variable names to keep the logic readable.
let score = 85;
let attendance = 92;
let passed = score >= 60 && attendance >= 80;
let excellent = score >= 90 || attendance >= 95;
console.log(passed); // true
console.log(excellent); // falseDo not rush to squeeze every condition into one line. Naming smaller conditions makes the program easier to read and debug.