JavaScript · Unit 1: JavaScript basics · Lesson 5 of 5
Booleans and comparisons
A boolean is true or false.
Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.
The idea
A boolean is true or false. Comparisons produce booleans: 5 > 3 is true and 2 >= 7 is false.
Use === to check whether two values are equal and !== for not equal. Avoid ==, which converts types first: "5" == 5 is true, which hides bugs, while "5" === 5 is false.
Combine conditions with && (and: both must be true), || (or: at least one) and ! (not).
Worked example
JavaScript
const age = 16;
console.log(age >= 13);
console.log(age === 16);
console.log("5" === 5);
console.log(age > 12 && age < 20);
It prints
true
true
false
true
Key terms
- Boolean
- true or false. && means and, || means or, ! means not.
- Comparison
- === equal, !== not equal, plus > < >= <=. Avoid ==, which converts types first.
Practise it in Code Academy
It has 4 exercises (predict the output, fill in the blank and write code from a prompt) and takes about 7 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.
Every lesson is free: no ads, no lives and no paywall.