Boolean Values

Every comparison has an answer: yes or no. In JavaScript, these answers are the values true and false, and you can print them:

console.log(10 < 20);
console.log("cat" === "dog");

This prints:

true
false

true and false are called boolean values, or booleans, after the mathematician George Boole. They are a third type of value, next to text and numbers: typeof true gives boolean. Write them without quotes; "true" in quotes is just text.

You can store a boolean in a variable like any other value, and then use the variable as a condition:

const age = 20;
const isAdult = age >= 18;
console.log("Adult:", isAdult);
if (isAdult) {
    console.log("You can vote");
}

This prints:

Adult: true
You can vote

Read the second line from right to left: JavaScript first compares age >= 18, which gives true, and then = stores that value in isAdult. The condition if (isAdult) means the same as if (isAdult === true); it's just shorter.

The names of boolean variables usually start with is or has (isAdult, hasTicket), so that they read like a yes-or-no question.

Instructions

Create a constant canAfford with the result of the comparison price <= budget. Then print it: console.log("Can I afford it?", canAfford);

Write an if statement with canAfford as its condition that prints I will buy it!.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

6/13

Next