Sprint View

Booleans

2 min read

Booleans

  • Booleans are one of the most fundamental data types in programming
  • A boolean can only have two values: true or false
  • Used to make decisions in code and control the flow of programs

The basic syntax of a boolean:

let isStudent = true;
let isRaining = false;
%%js

let isActive = true;
console.log(isActive);
console.log("Boolean value: " + isActive);
console.log("Boolean value: " + isActive);
<IPython.core.display.Javascript object>

Usage: Boolean Comparisons

You can use comparison operators to create boolean values.

Code Runner Challenge

Run code, then change to your own conditions

View IPYNB Source
%%js

let age = 15;
let isAdult = age >= 18;
let isTeenager = age >= 13 && age <= 19;

console.log("Is adult: " + isAdult);
console.log("Is teenager: " + isTeenager);

// Test with different ages
console.log(isAdult && isTeenager); // false - can't be both adult and teenager
console.log(isAdult || isTeenager); // true - at least one is true

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
<IPython.core.display.Javascript object>

Boolean Operators

Booleans can be combined using logical operators like && (and), || (or), and ! (not)

Code Runner Challenge

Create a function that checks if a number is positive and even

View IPYNB Source
%%js

// CODE_RUNNER: Run code, then change to your own conditions
let hasLicense = true;
let hasCar = false;
let canDrive = hasLicense && hasCar;

console.log("Has license: " + hasLicense);
console.log("Has car: " + hasCar);
console.log("Can drive: " + canDrive);

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

HomeWork Boolean

Write a function that checks if a number is positive AND even

Test it with an input of 8

Hint: use the modulo operator (%) to check if a number is even, and comparison operators to check if it’s positive.

%%js
// CODE_RUNNER: Create a function that checks if a number is positive and even

function isPositiveAndEven(num) {
    let isPositive = num > 0;
    let isEven = num % 2 === 0;
    return isPositive && isEven;
}

console.log(isPositiveAndEven(8)); // true

Course Timeline