Skip to content
portfolio/howtos/Learning JavaScript/

Chapter 04

Operators & Expressions

An operator is a symbol that combines values to produce a new one. + is an operator. A bit of code that produces a value - like 2 + 3 - is called an expression. You've already used a few; here's the full toolkit for beginners.

Maths

console.log(10 + 3);  // 13   addition
console.log(10 - 3);  // 7    subtraction
console.log(10 * 3);  // 30   multiplication
console.log(10 / 3);  // 3.333...  division
console.log(10 % 3);  // 1    remainder (what's left over)

The last one, %, is the "remainder" or "modulo" operator - it gives what's left after dividing. 10 % 3 is 1 because 3 goes into 10 three times (9) with 1 left over. It's surprisingly useful: number % 2 is 0 for even numbers and 1 for odd ones.

Note
Normal maths order applies: * and / happen before + and -. Use brackets to force an order: (2 + 3) * 4 is 20, but 2 + 3 * 4 is 14.

Handy Shortcuts

Updating a variable using itself is so common there are shortcuts for it:

let count = 5;

count = count + 1; // the long way
count += 1;        // the same thing, shorter
count++;           // even shorter: add exactly 1

console.log(count); // 8

There's +=, -=, *=, and /= for each operation, plus ++ (add one) and -- (subtract one).

Comparing Values

Comparison operators ask a question and answer with a boolean - true or false:

console.log(5 > 3);    // true   greater than
console.log(5 < 3);    // false  less than
console.log(5 >= 5);   // true   greater than or equal
console.log(5 <= 4);   // false  less than or equal
console.log(5 === 5);  // true   equal to
console.log(5 !== 3);  // true   not equal to
Warning
To check if two things are equal, use three equals signs: ===. This is different from the single = (which assigns a value) and safer than two equals == (which does surprising conversions). Rule of thumb: always use === and !==.
console.log(5 === "5"); // false - a number is not a string
console.log(5 == "5");  // true  - avoid this; == hides the difference

Combining Answers: Logic

You often need to combine several true/false checks. Three operators do this:

  • && ("and") is true only if both sides are true.
  • || ("or") is true if either side is true.
  • ! ("not") flips true to false and false to true.
const age = 20;
const hasTicket = true;

console.log(age >= 18 && hasTicket); // true  - old enough AND has a ticket
console.log(age < 18 || hasTicket);  // true  - one side is true
console.log(!hasTicket);             // false - flips true

These become the heart of decision-making in the next chapters. Try building your own expressions in the Console until the results stop surprising you.