true and false
A comparison gives back one of two values: true or false. These are called booleans.
console.log(5 > 3);
console.log(5 < 3);
console.log(4 === 4);
console.log(4 !== 4);true false true false
=== checks if two values are the same. !== checks if they are different. You'll also see <= (less than or equal) and >= (greater than or equal).
Try it
What does this print?
console.log(3 === "3");
if
if runs the code inside its curly braces only when the condition in the brackets is true.
let temp = 30;
if (temp > 25) {
console.log("It's hot");
}
console.log("Done");It's hot Done
If temp were 20, the first message would be skipped and only Done would print.
else and else if
else runs when the condition was false. else if lets you check another condition. JavaScript checks them from the top and runs the first one that's true, then skips the rest.
let score = 72;
if (score >= 90) {
console.log("A");
} else if (score >= 70) {
console.log("B");
} else {
console.log("Keep practising");
}B
Try it
What does this print?
let n = 7;
if (n > 10) {
console.log("big");
} else if (n > 5) {
console.log("medium");
} else {
console.log("small");
}
Combining conditions
&& means and: both sides must be true. || means or: at least one side must be true. ! flips true to false and false to true.
let age = 15;
let hasTicket = true;
if (age >= 13 && hasTicket) {
console.log("You can go in");
}You can go in
Try it
What does this print?
let a = true;
let b = false;
console.log(a && b);
Common mistakes
if (x = 5) stores 5 in x instead of comparing. The condition is then always treated as true. Use === to compare.
== tries to convert types before comparing, so 3 == "3" is true. That causes surprises. Stick with ===.
If you check score >= 50 before score >= 90, a score of 95 matches the first one and never reaches the second. Put the strictest check at the top.
Recap
- Comparisons give true or false.
- if runs code only when its condition is true.
- else if and else handle the other cases. Only one block runs.
- && means and, || means or, ! means not.