Beginner · JavaScript basics · topic 20 of 64 · 30 min
Operators and conditions
Explanation
Maths operators
console.log(7 + 2); // 9
console.log(7 - 2); // 5
console.log(7 * 2); // 14
console.log(7 / 2); // 3.5
console.log(7 % 2); // 1 (remainder)
console.log(2 ** 3); // 8 (power)Comparisons
A comparison gives a boolean. Use === (strictly equal) and !== (not equal). They compare both the value and the type. The older == converts types first, so 5 == "5" is true, which hides bugs. Always use ===.
console.log(5 === 5); // true
console.log(5 === '5'); // false (number vs string)
console.log(10 > 3); // true
console.log(18 >= 18); // trueMaking decisions with if
function grade(marks) {
if (marks >= 90) {
return 'A';
} else if (marks >= 75) {
return 'B';
} else if (marks >= 35) {
return 'C';
} else {
return 'Fail';
}
}
console.log(grade(82)); // 'B'Logic: and, or, not
- a && b is true only when both are true (has ticket AND has ID).
- a || b is true when at least one is true (paid by UPI OR card).
- !a flips true and false (!isLoggedIn means "not logged in").
Truthy and falsy
In a condition, JavaScript treats some values as false: false, 0, "" (empty string), null, undefined and NaN. These are called falsy. Everything else is truthy, even "0" and an empty list [].
Short forms
const age = 20;
const label = age >= 18 ? 'adult' : 'minor'; // ternary: condition ? yes : no
const userCity = null;
const city = userCity ?? 'Not given'; // ?? gives a default for null/undefined
console.log(label, city); // adult Not givenA switch statement compares one value against many fixed cases. It is handy for things like a menu choice, but a chain of if / else if is fine for most checks.
Watch the lesson
Operators and conditions · 1/6
Operators work on values. Plus, minus, times, divide, and percent for the remainder.
Prefer a video by a teacher? Find free videos on “javascript if else comparison logical operators beginners” on YouTube ↗
In real life: Free delivery rule
A food delivery app decides the delivery fee with conditions: if the order total is at least 199 rupees and the user is a member, delivery is free; else if the total is at least 199, the fee is 20 rupees; else the fee is 40 rupees. The same if / else if logic decides discounts, ticket prices for children and senior citizens, and exam grades.
Practice (0/3 done)
Write a function isEven(n) that returns true when n is even and false when it is odd. Use the % operator.
Write a function ticketPrice(age) for a museum: children under 5 enter free (0), ages 5 to 17 pay 20, ages 60 and above pay 25, and everyone else pays 50.
Write a function deliveryFee(total, isMember): free (0) when total is at least 199 and the user is a member; 20 when total is at least 199 but not a member; otherwise 40.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.