Comparison Operators

Grade 3, page 5 of 11. A one-minute read.

Now for something new. Comparison operators compare two values and give you back a boolean: true or false.

OperatorMeaningExampleResult
>greater than10 > 5true
<less than10 < 5false
>=greater than or equal to5 >= 5true
<=less than or equal to4 <= 3false
===equal to5 === 5true
!==not equal to5 !== 5false
JavaScript
const myAge = 15;
const votingAge = 18;

console.log(myAge >= votingAge);
console.log(myAge < votingAge);
console.log(myAge === 15);
console.log(myAge !== 15);

It prints

false
true
true
false

These are the questions your program will ask before it makes decisions. "Is the user old enough?" "Is the password correct?" "Has the player run out of lives?" Each question gives a true or false answer, and in Grade 4, your program will act on that answer.

TipRemember the alligator

If you always forget which way round < and > go, imagine the symbol is a hungry alligator's mouth. The alligator always wants to eat the bigger number. In 10 > 5, the mouth opens toward 10. 🐊

Comparing strings

You can compare strings too. JavaScript compares them alphabetically, character by character, a bit like a dictionary:

JavaScript
console.log("apple" < "banana");
console.log("cat" > "car");
console.log("Zebra" < "apple");
console.log("10" < "9");

It prints

true
true
true
true

The first two make sense: "apple" comes before "banana" in the dictionary, and "cat" comes after "car" (because "t" comes after "r").

The last two are surprising:

  • Capital letters come before lowercase letters. Every uppercase letter is "less than" every lowercase letter, so "Zebra" < "apple".
  • Numbers in strings are compared as text, not as numbers. "10" starts with "1", which comes before "9", so "10" < "9". If you want to compare numbers, make sure they're actual numbers, not strings!

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning