Learn how to calculate, compare values with === and make your program take decisions with if and else.
Open this lesson in KodokonAn 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.
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)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.
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); // trueTime 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 { }.
const age = 17;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
// Prints: You are a minor.5 === "5"?if / else structure, when does the else block run?