Lesson 7 - Booleans
JavaScript Logical Conditions and Booleans
Booleans are special values in JavaScript that can only
be true or false (always lowercase!).
They are often used with logical conditions to control
how your program runs.
let x = true;
let y = false;
console.log(x, y);
let isHungry = true;
if (isHungry) {
console.log("Time to eat!");
}
Comparison Operators:
| Equal | a === b |
Not Equal | a !== b |
| Greater than | a > b |
Less than | a < b |
| Greater than or equal | a >= b |
Less than or equal | a <= b |
💡 In JavaScript use three equal signs ===
to compare values. A single = stores a value
in a variable.
console.log(5 > 3); // true
console.log(10 === 5); // false
console.log(10 !== 5); // true
Checking a list with .includes() tells you
if a value is a member of an array or not. It gives back
true or false. Put ! in
front to check that it is not in the list.
let favorite = "chocolate";
let found = fruits.includes(favorite);
console.log(found);
Boolean Operators used to combine the values of multiple boolean values.
let height = 52;
let isAllowed = (age >= 8 || height >= 48);
console.log(isAllowed);
let notAllowed = !isAllowed;
console.log(notAllowed);
&& - true if both conditions are true.||
- true if one of the conditions is true.!
- flips the result.
Tip: Conditions let your program make decisions. Try changing the values and see how the program follows different paths.
True or False?
console.log(2 === 3);
💡 Predict the output.
Check Age
if (age >= 18) {
console.log("Adult");
} else {
console.log("Child");
}
💡 What will it print?
Guess favorite food
let guess = "Pizza";
let found = favorite.includes(guess);
if (found) {
console.log("Yes, thats my favorite food");
}
if (!found) {
console.log("No, I don't like that");
}
💡 Change guess and make your own favorite food list.
Even or Odd?
if (number % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}
💡 Try changing the number.
Pass or Fail
Store an exam score in a variable. If it’s 60 or higher, print "Pass"
if (score >= 60) {
console.log("Pass");
}
💡 Add an else that prints "Fail", then try a score of 40.
Using &&
if (temp > 20 && temp < 30) {
console.log("Nice weather!");
} else {
console.log("Not nice.");
}
💡 Predict the output.
Using ||
if (day === "Saturday" || day === "Sunday") {
console.log("Weekend!");
} else {
console.log("Weekday.");
}
💡 Try changing the value of day.
Using !
if (!isRaining) {
console.log("Go outside!");
} else {
console.log("Take an umbrella.");
}
💡 Predict the output.
If…Else if…Else
if (score >= 90) {
console.log("Excellent");
} else if (score >= 60) {
console.log("Good");
} else {
console.log("Try harder");
}
💡 What will it print?
Mystery Output
let y = 10;
if (x * 2 === y) {
console.log("Equal!");
} else {
console.log("Not equal!");
}
❓ Predict the output without running first.