In the previous lesson, you stored yes-or-no answers like hasRainJacket by typing true or false yourself. That works when you already know the answer. But the most useful question about your hiking pack is one you can’t answer by looking at it: Is it light enough to carry?
Your pack from the warm-up weighed 6 kg. Say the trail guide recommends a pack under 8 kg. You could check that in your head, but you’d have to check again every time you swap the tent or add water. In this lesson, you’ll let JavaScript compare the two numbers and hand you the Boolean answer instead.
By the end, you’ll be able to predict the result of a comparison between numbers, calculations, or strings, and write a comparison that checks whether a value meets a stated limit, such as “at most 8 kg.”
Ask JavaScript a Question With < and >
You already know the symbols < and > from math class. In JavaScript, they’re comparison operators. A comparison operator takes two values, checks how they relate, and gives back a Boolean: true if the relation holds and false if it doesn’t.
Start the Node REPL by typing node in the integrated terminal. Before you type each line below, predict whether it’ll give back true or false:
> 6 < 8
true
> 6 > 8
false
> 8 > 6
true
Read < as “is less than” and > as “is greater than.” So 6 < 8 asks whether six is less than eight, and JavaScript answers true. The results have no quotes, because they’re the same Booleans you typed by hand in the previous lesson. This time, JavaScript worked them out for you.
You can also compare a calculated value directly, such as your warm-up pack’s total. Predict this result, too:
> 2.5 + 1.5 + 2 < 8
true
JavaScript finishes the arithmetic before it compares, so this line asks whether 6 is less than 8, with no parentheses needed.
Store the Answer in a Variable
A comparison produces a value, just as addition does. That means you can store its result in a variable and use it later. Enter .exit to leave the REPL, then create a file named limit.js in your scratch/ folder and add this script:
const tentKg = 2.5;
const sleepingBagKg = 1.5;
const foodKg = 2;
const limitKg = 8;
const totalKg = tentKg + sleepingBagKg + foodKg;
const isLight = totalKg < limitKg;
console.log(`Pack: ${totalKg} kg, light: ${isLight}`);
Save the file, then run it in the terminal with node scratch/limit.js:
Pack: 6 kg, light: true
In the line const isLight = totalKg < limitKg;, JavaScript first compares totalKg with limitKg, then stores the Boolean result in isLight. Your program now holds the answer, the same way totalKg holds the sum.
Decide What Happens Right at the Limit
Now say the trail guide changes its advice: a pack of at most 8 kg is fine. Under the new rule, a pack of exactly 8 kg counts as light, too. But totalKg < limitKg still asks whether the pack is under 8 kg, so it no longer matches the rule.
The value where a rule switches from one answer to the other is its boundary, and you decide whether the boundary value itself counts. To include it, JavaScript has two more operators:
<=means “is less than or equal to.”>=means “is greater than or equal to.”
You write each one as two characters with no space, and the equals sign always comes second. To test the new rule right at its boundary, pack two liters of water, which weigh about 2 kg. Add the water to limit.js and change the comparison to <=:
const tentKg = 2.5;
const sleepingBagKg = 1.5;
const foodKg = 2;
const waterKg = 2;
const limitKg = 8;
const totalKg = tentKg + sleepingBagKg + foodKg + waterKg;
const isLight = totalKg <= limitKg;
console.log(`Pack: ${totalKg} kg, light: ${isLight}`);
The pack now weighs exactly 8 kg. Predict what the script prints, then save and run it again:
Pack: 8 kg, light: true
Now 8 kg counts as light. A comparison that counts the boundary value, like <= or >=, is inclusive. One that leaves it out, like < or >, is exclusive.
To see the whole picture, try the weights just below, at, and just above the limit with < and <=. Predict all six results, then start the REPL again with node and check them:
> 7.5 < 8
true
> 8 < 8
false
> 8.5 < 8
false
> 7.5 <= 8
true
> 8 <= 8
true
> 8.5 <= 8
false
The two operators agree everywhere except at the boundary itself. That’s why the boundary is the value worth testing whenever you write a comparison: away from it, the wrong operator still gives the right answer.
To see where the two operators part ways, try the explorer below. Drag totalKg from 6 kg up to 10 kg, and at each weight switch the comparison between < and <=, predicting isLight before you look:
Switching the operator changed the result only when the marker sat right on 8 kg: there, < printed light: false and <= printed light: true.
So how do you pick the right operator? Read the rule’s wording closely, because it tells you whether the boundary counts:
| The rule says | The boundary counts? | Comparison |
|---|---|---|
| “under 8 kg” or “less than 8 kg” | No | totalKg < 8 |
| “at most 8 kg” or “up to 8 kg” | Yes | totalKg <= 8 |
| “over 8 kg” or “more than 8 kg” | No | totalKg > 8 |
| “at least 8 kg” | Yes | totalKg >= 8 |
When the wording leaves you unsure, ask what should happen at exactly the boundary value, and pick the operator that gives that answer. For more practice, the button below opens a mentor conversation where you get limit rules in plain words, one at a time, and pick the operator for each.
Compare Text, One Character at a Time
Comparison operators work on strings, too. Instead of asking which value is larger, they ask which string comes first in order, similar to how words are sorted in a dictionary.
JavaScript compares two strings character by character from the left. The first position where the characters differ decides the result. For the lowercase letters a to z, that gives you alphabetical order. Predict these results, then check them in the REPL:
> "map" < "tent"
true
> "tarp" < "tent"
true
> "tent" < "map"
false
In "tarp" < "tent", both strings start with t. So JavaScript moves on to the second character and compares a with e. The letter a comes first in the alphabet, so the answer is true.
Sometimes one string runs out before any character differs. Then the shorter string comes first. If both strings are identical, neither comes first, so < and > give false, while <= and >= give true:
> "map" < "maps"
true
> "map" < "map"
false
> "map" <= "map"
true
Uppercase letters change the alphabetical picture. Behind the scenes, JavaScript stores text as numeric codes called UTF-16 code units, and it compares those numbers rather than looking anything up in an alphabet. The uppercase letters A to Z all have smaller codes than the lowercase letters a to z, so any of them comes before any lowercase letter:
> "Tent" < "map"
true
T comes before m because it’s uppercase, even though t comes after m in the alphabet. Letters outside A to Z and a to z, such as É, have their own codes, so this order isn’t a full alphabetical sort. Keep this in mind when you compare words that mix uppercase and lowercase letters.
Number-Like Text Is Still Text
The same character-by-character rule applies to strings that contain digits. In the previous lesson, you saw that "true" looks like a Boolean but is text. Digits in quotes work the same way. Predict both results before you run them:
> 10 < 9
false
> "10" < "9"
true
The first line compares two numbers, and ten isn’t less than nine. The second line compares two strings, so JavaScript looks at the first characters, "1" and "9". The character "1" comes before "9", so JavaScript decides right there and never looks at the 0.
Both comparisons give correct results, but only the first answers a question about weights. Weights often arrive as text, for example from a form, so a later lesson in this course shows you how to turn text like "10" into the number 10.
Until then, remember that a comparison orders values as text only when both of them are strings. If just one side is a string, JavaScript quietly turns that text into a number before comparing:
> "10" < 9
false
Here "10" becomes the number 10, and 10 isn’t less than 9. Mixing the two types makes the result easy to misread, so it’s safer to convert text yourself, which that lesson covers.
For more practice with character-by-character ordering, the next button starts a short round of string predictions with the mentor:
Check Your Understanding
Before you move on, predict the Boolean result of each comparison below and say in one sentence why you expect it:
2.5 + 1.5 >= 47.5 > 7.5"rope" > "map""25" < "3"
Then type them into the REPL to check your predictions. You can also open the box below to compare your results:
> 2.5 + 1.5 >= 4
true
> 7.5 > 7.5
false
> "rope" > "map"
true
> "25" < "3"
true
The sum is 4, and >= counts the boundary, so the first result is true. A value is never greater than itself, so 7.5 > 7.5 is false. The letter r comes after m, so "rope" comes after "map". Finally, "25" and "3" are strings, and the character "2" comes before "3", even though 25 is the larger number.
Now write a comparison of your own. For a day hike, the trail guide also says to bring at least 2 liters of water. Enter .exit to leave the REPL, then add a variable named waterLiters to a new script in your scratch/ folder, set it to 1.5, and store the answer to “Is there enough water?” in a variable called hasEnoughWater. Print the answer with a template literal.
Run your script, then change waterLiters to 2 and run it again. That second run tests the boundary, and “at least” means 2 liters should count as enough. When you’re ready, compare your script with this one:
const waterLiters = 1.5;
const hasEnoughWater = waterLiters >= 2;
console.log(`Enough water: ${hasEnoughWater}`);
Enough water: false
With waterLiters set to 2, the script prints Enough water: true, because >= is inclusive. If your version printed false for 2 liters, check whether you used > instead of >=.
Get Ready for Your First Exercise
Your next step, Check Weights Against a Limit, is the first coding exercise of this course. You’ll write code right here in the RealJS browser editor, inside a supplied wrapper like the one from the previous lesson. Your return line will hand back the result of a comparison instead of a number.
When you press Run Tests, the test runner calls your code with several different weights and tells you which checks passed. Run the tests early and often. If a check fails or an error appears, read its message for clues about what to change, then try again. If you’d like more room for the editor and the feedback, use the Full screen option.