Kodokon kodokon.com

Operators and conditions (if/else, comparisons, ===)

Learn how to calculate, compare values with === and make your program take decisions with if and else.

7 min · 3 questions

Open this lesson in Kodokon

An operator is a symbol that performs an operation on values. You already know the arithmetic operators from school: + (addition), - (subtraction), * (multiplication) and / (division). JavaScript adds %, the modulo, which gives the remainder of an integer division: handy, for example, for finding out whether a number is even.

JAVASCRIPT
const a = 10;
const b = 3;
console.log(a + b); // Prints: 13
console.log(a - b); // Prints: 7
console.log(a * b); // Prints: 30
console.log(a % b); // Prints: 1 (the remainder)
The basic arithmetic operators

To take decisions, a program needs to compare values. A comparison is a question whose answer is a boolean: true or false. The comparison operators are > (greater than), < (less than), >= (greater than or equal), <= (less than or equal), === (strictly equal) and !== (strictly not equal). The === operator checks that two values are identical and of the same type.

JAVASCRIPT
console.log(5 > 3);     // true
console.log(5 < 3);     // false
console.log(5 >= 5);    // true
console.log(5 === 5);   // true
console.log(5 === "5"); // false: different types
console.log(5 !== 3);   // true
Each comparison returns true or false

Time for decisions! The if statement runs a block of code only if a condition is true. The else block runs when the condition is false. The condition is written between parentheses, and each block between curly braces { }.

JAVASCRIPT
const age = 17;

if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}
// Prints: You are a minor.
A decision with if and else

Knowledge check

Make sure you remember the key points of this lesson.

  1. What is the value of the expression 5 === "5"?
    • true
    • false
    • 5
  2. Which operator means "strictly not equal to"?
    • !==
    • ==
    • <>
    • =/=
  3. In an if / else structure, when does the else block run?
    • Always
    • When the if condition is true
    • When the if condition is false