True and False as Values

Picture yourself getting ready for a weekend hike. Your backpack has a weight limit, and you have a short list of gear with a weight for each item. Before you leave, you want answers to three plain questions. How heavy is the pack? Is it under the limit? Is the rain jacket in there?

Programs ask questions like these all the time. Some answers are numbers, like a total weight. Others are yes or no. In this course, you’ll learn how JavaScript writes down a yes-or-no answer, how it compares values to produce one, and how it turns numbers that arrive as text, like "2.5", into numbers you can actually add.

Build Toward a Pack Checker

By the end of this course, you’ll build the calculation core of an adventure pack checker on RealJS. It takes gear weights that arrive as text, converts them into numbers, totals them, reports whether the total stays within a weight limit, and produces a tidy line of text to show the result.

Larger programs use the same pieces whenever they check a form, a budget, or a score. Each lesson adds one piece, and you’ll practice it on its own before the project combines them.

This course builds on Values, Names, and Text, an earlier course in JavaScript Basics. You’ll use variables, arithmetic, strings, and template literals, and you’ll run short scripts with Node.js in VS Code. If you arrived here directly, those are the skills you’ll need. If some of them feel rusty, that’s okay! The first activity below gives you a chance to check.

Work Through This Course

Keep your course folder open in VS Code, with the integrated terminal open in that same folder. The lessons show short scripts that you can type into a file in your scratch/ folder and run with node. Typing them yourself and changing a value teaches you more than reading the output.

Alongside your local scripts, you’ll solve coding exercises right here on RealJS. There, a test runner supplies the inputs and checks your answer for you. You’ll get a quick reminder of how those exercises work later in this lesson, and the first one comes after the next lesson.

Some lessons also include buttons that open a conversation with a mentor, prefilled with a question about the passage you just read. They’re optional, and each lesson works without them.

Warm Up With a Pack Total

Start with something you already know how to do. Before you read the example below, create a file named pack.js in your scratch/ folder and write a short script that does three things:

  1. Stores the weights of three pieces of gear in variables, using kilograms
  2. Adds them up into a fourth variable
  3. Prints a sentence about the total with a template literal

Run it with node scratch/pack.js in the integrated terminal. Then compare your script with this version, which uses a tent, a sleeping bag, and some food:

Language: JavaScript
const tentKg = 2.5;
const sleepingBagKg = 1.5;
const foodKg = 2;
const totalKg = tentKg + sleepingBagKg + foodKg;

console.log(`Your pack weighs ${totalKg} kg.`);
Language: Program Output
Your pack weighs 6 kg.

Your names and weights can differ. If your script printed a sentence with the right total, then you’re ready for this course. If the total looks off, check that each weight is a number without quotes, because quoted digits are text, and the + operator would join them instead of adding them.

Write Down a Yes-or-No Answer

The total answers a “how much” question with a number. Now consider a different question about the same pack, such as whether the rain jacket is in it. There’s no amount to calculate here. The answer is either yes or no.

JavaScript has a value made exactly for that. A Boolean is a value that can only be true or false. You write them as plain lowercase words, with no quotes around them, and you store them in variables the same way you store numbers and strings.

Add these two lines to the end of pack.js:

Language: JavaScript
const hasRainJacket = false;

console.log(`Rain jacket packed: ${hasRainJacket}`);
Language: Program Output
Rain jacket packed: false

The variable hasRainJacket now holds the answer to one question. A template literal can include a Boolean just like a number, so the sentence shows the word false.

Now pack the jacket. Change false to true in the first line, save the file, and run it again. You’ll see Rain jacket packed: true. Feel free to swap in a piece of gear you’d never leave behind, such as hasSnacks or hasMap, and set it to whatever is true for your own trip.

Notice that storing a Boolean doesn’t make anything happen. true isn’t a command to print something or to start packing. It’s an answer that your program keeps, so you can show it, pass it on, or use it later. In an upcoming JavaScript Basics course, you’ll use answers like this one to let a program choose what to do next.

Tell a Boolean Apart From Text

JavaScript is strict about how you spell these two values. They’re always lowercase, and they never have quotes. The Node REPL shows what happens when you break either rule. Start the REPL by typing node in the terminal, then try these lines:

Language: JavaScript
> true
true
> "true"
'true'
> True
Uncaught ReferenceError: True is not defined

The first line gives back the Boolean true. The second gives back 'true' with quotes. Those quotes are the REPL’s way of telling you that this value is a string made of the four characters t, r, u, and e. It looks like a yes, but to JavaScript it’s text, just like "yes" or "hiking".

The third line shows what happens with a capital letter. Without quotes, JavaScript reads True as the name of a variable. You never created a variable called True, so JavaScript reports a ReferenceError and tells you which name it couldn’t find. The fix is to write it in lowercase. When you’re done, leave the REPL with .exit.

The difference between true and "true" is easy to miss, because console.log() prints them the same way. Try this in a script:

Language: JavaScript
const answer = true;
const label = "true";

console.log(answer);
console.log(label);
Language: Program Output
true
true

Both calls print true, even though only answer holds a Boolean. When you need to know which kind of value you have, the REPL’s quotes are the better clue. That distinction matters because the comparisons in the next lesson produce Booleans, and the exercise tests check for a real true or false, not for text that happens to spell one.

Pass a Boolean Along

Like any other value, a Boolean can move from one variable to another. Back in the REPL, try this:

Language: JavaScript
> const hasRainJacket = true
undefined
> const readyForRain = hasRainJacket
undefined
> readyForRain
true

You can ignore the undefined lines. The REPL prints them after every const line, because creating a variable doesn’t give back an answer to show. The last line shows that readyForRain now holds the same Boolean as hasRainJacket, without any quotes.

Return an Answer to the Exercise Runner

Your first coding exercise in this course comes right after the next lesson. It uses the same kind of supplied wrapper that you met in Values, Names, and Text, so here’s a short reminder of how it works.

On-site exercises run in a code editor in your browser, with no file to save and no node command to type. When you run the tests, the runner tries your code with several inputs and reports which checks passed. If one fails or shows an error, read its message for clues, change one thing, and run the tests again. Run them early and often. For more room, use the Full screen option.

Once you’ve solved an exercise, its code might look like this, with your work on the line inside the braces:

Language: JavaScript
export function packWeight(tentKg, foodKg) {
  return tentKg + foodKg;
}

Each part has a job:

  • The first line and the closing brace are supplied wiring. Leave them as they are, because the runner needs them.
  • tentKg and foodKg are the input names. You don’t set their values yourself. For one test, the runner calls packWeight(2, 1.5). The first value goes into tentKg and the second into foodKg, in order. The next test might call packWeight(3, 0.5) instead. An exercise’s Examples show each test as name(values) -> answer, so packWeight(2, 1.5) -> 3.5 means that call should hand back 3.5.
  • The return line is the part you write. It calculates the answer from the inputs and hands that answer back to the runner, which then checks it.

The return line is different from console.log(). If you write console.log(tentKg + foodKg) instead, the total will appear as output, but the runner won’t receive an answer to check, so the test will fail. Use console.log() to see values while you work, and return to hand over your answer.

In this course, many of your return lines will hand back a Boolean instead of a number. You could write return true;, but then the answer would be yes for every pack, no matter what the inputs are. To return an answer that depends on the weights, you need a way to calculate a Boolean, and that’s exactly what comparisons do.

Check Your Understanding

Before you move on, predict what the REPL gives back for each of these three lines. Decide which one is a Boolean, which one is text, and which one causes an error:

  • false
  • "false"
  • False

Next, look at const isHeavy = false. What does isHeavy store, and what does the REPL display after this line? Type all four lines into the REPL, then isHeavy on its own, to check. You can also open the box below:

Language: JavaScript
> false
false
> "false"
'false'
> False
Uncaught ReferenceError: False is not defined
> const isHeavy = false
undefined
> isHeavy
false

Only false without quotes is a Boolean. "false" is a string, and False is an unknown variable name. The declaration stores the Boolean false in isHeavy, but the REPL displays undefined, because creating a variable gives back nothing to show. Typing isHeavy on its own reveals that stored value.

As a final check, explain to yourself in one sentence why an exercise that asks whether a pack is light enough should return true and not "true". If your sentence mentions that one is a yes-or-no value and the other is text, you’ve got it.

In the next lesson, Compare Numbers and Text With Boundaries, you’ll stop typing true and false by hand. Instead, you’ll ask JavaScript to compare two values, such as a pack’s total and its weight limit, and it will hand you back the Boolean answer.

Become a Member to join the conversation.