Boolean Expressions
Learn about boolean expressions
Boolean Expressions
What are boolean expressions?
Boolean expressions are combinations of values and operators that result in true or false. They let you check complex conditions in your code.
Benefits of boolean expressions?
- Check multiple conditions at once
- Create complex decision logic
- Combine comparisons with logical operators
- Make code more readable than single conditions
- Essential for game mechanics and validations
const playerHealth = 50;
const maxHealth = 100;
const hasShield = true;
// Simple comparisons
console.log(playerHealth > 0); // true
console.log(playerHealth === 50); // true
console.log(playerHealth !== maxHealth); // true
// AND operator
const canAttack = playerHealth > 0 && hasShield;
console.log(canAttack); // true
// OR operator
const canMove = playerHealth > 0 || hasShield;
console.log(canMove); // true
// Complex expressions
const hasAmmo = true;
const isReloading = false;
const canShoot = hasAmmo && !isReloading && playerHealth > 0;
if (canShoot) {
console.log("Player can shoot!");
}
What does this code do?
- Uses comparison operators to check conditions
- Combines conditions with
&&(AND) - both must be true - Combines conditions with
||(OR) - at least one must be true - Uses
!(NOT) to flip a boolean value - Stores complex expressions in variables for reuse
Code Runner Challenge
boolean-expressions
View IPYNB Source
%%js
// CODE_RUNNER: boolean-expressions
const health = 50;
const hasShield = true;
const result = health > 30 && hasShield;
console.log(result);
const orResult = health < 20 || hasShield;
console.log(orResult);
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...