BeginnerLesson 3 of 304 min read

Operators: maths, comparison and logic

Do maths, compare values and combine conditions with JavaScript operators, and avoid the classic == trap.

In this lesson you will

  • Calculate with arithmetic operators
  • Compare values to get true or false
  • Combine conditions with AND, OR and NOT
  • Use === instead of ==

About 15 minutes

Teaching the computer to calculate and decide

You are at a shop. You buy three notebooks at 120 rupees each, add one pen at 45, and wonder if your 500 is enough. That small story used addition, multiplication and a comparison. JavaScript does the same with operators: symbols that take values and produce a result.

Arithmetic operators

Operator Meaning Example Result
+ Add 7 + 3 10
- Subtract 7 - 3 4
* Multiply 7 * 3 21
/ Divide 7 / 2 3.5
% Remainder (modulo) 7 % 2 1
** Power 2 ** 3 8

The remainder operator % looks strange at first, but it is wonderfully useful. 10 % 2 is 0, so a number is even when n % 2 === 0. It is also how clocks work: 15:00 is 3 o’clock because 15 % 12 is 3.

Work out the bill: 3 notebooks at 120, plus one pen at 45. Store the total and print it.

const notebooks = 3 * 120;
const pen = 45;
// create total and print it

Add the two constants, then console.log the result.

const notebooks = 3 * 120;
const pen = 45;
const total = notebooks + pen;
console.log(total);   // 405

Order of operations

Like in school maths, multiplication and division happen before addition and subtraction. Brackets let you take control.

console.log(2 + 3 * 4);     // 14, multiplication first
console.log((2 + 3) * 4);   // 20, brackets first
console.log(10 - 4 - 3);    // 3, left to right
Brackets cost nothing

Even when you know the order, add brackets to make the intention obvious to the next reader. (a * b) + c is easier to read than a * b + c.

Comparison operators: asking questions

Comparison operators ask a question about two values and answer with true or false. These booleans power every decision in your programs.

Operator Asks Example Result
=== Equal in value and type? 5 === 5 true
!== Not equal? 5 !== 3 true
> Greater than? 3 > 5 false
< Less than? 3 < 5 true
>= Greater or equal? 5 >= 5 true
<= Less or equal? 4 <= 3 false

Why three equals signs?

JavaScript has two kinds of equality. The strict one, ===, compares value and type. The loose one, ==, tries to convert types first, which produces odd results.

console.log(5 === "5");   // false: number vs string
console.log(5 == "5");    // true: loose, converts first (avoid)
console.log(0 == false);  // true: surprising!
console.log(0 === false); // false: clear
Common mistake

Writing a single = when you meant to compare. = assigns, === compares. if (x = 5) overwrites x instead of checking it.

Print the answer to each question: is 18 an adult age (18 or more)? Is 7 odd (remainder 1 when divided by 2)?

const age = 18;
const n = 7;
console.log(/* is age at least 18? */);
console.log(/* is n % 2 equal to 1? */);

Replace each comment with a comparison: age >= 18 and n % 2 === 1.

const age = 18;
const n = 7;
console.log(age >= 18);
console.log(n % 2 === 1);

Logical operators: combining questions

Operator Name True when
&& AND both sides are true
|| OR at least one side is true
! NOT flips true to false and back
const age = 20;
const hasTicket = true;

console.log(age >= 18 && hasTicket);   // true
console.log(age < 13 || age > 65);     // false
console.log(!hasTicket);               // false

Read them aloud: “age is at least 18 and has a ticket”. The code reads almost like English, which is the goal. AND is strict, OR is flexible, NOT is a mirror.

Combining strings with +

console.log("Java" + "Script");   // JavaScript
console.log("Age: " + 25);        // Age: 25
console.log("5" + 3);             // 53  (text!)
console.log("5" - 3);             // 2   (maths)

When one side of + is text, JavaScript joins instead of adds. That is why "5" + 3 gives "53". The other maths operators convert text to numbers, which makes this a classic trap. The next lesson shows a cleaner way to build text.

Increment and decrement

let lives = 3;
lives--;           // 2
lives--;           // 1
console.log(lives);

let level = 1;
level += 1;        // 2
level *= 5;        // 10
console.log(level);
Good to know

An expression is anything that produces a value, like 3 + 4 or age >= 18. A statement is an instruction, like const x = 3 + 4;. Programs are made of statements built from expressions.

Worked example: a discount rule

Let us combine everything in one small, realistic problem. A shop gives 10 percent off when the total is at least 1000, and an extra 5 percent for members. We want the final price. Read the code slowly and say each line aloud in plain words.

const total = 1200;
const isMember = true;

let discount = 0;
if (total >= 1000) discount = 10;
if (total >= 1000 && isMember) discount = 15;

const finalPrice = total - total * discount / 100;
console.log(`Discount: ${discount}%`);
console.log(`You pay: ${finalPrice}`);

Notice how the comparisons produce true or false, the logical operator joins two questions, and the arithmetic finishes the job. Almost every real calculation on a website follows this pattern: ask questions about the data, then calculate.

Change total to 800 and isMember to false, predict the output, then run it. Next try total 1000 and isMember true.

const total = 1200;
const isMember = true;
let discount = 0;
if (total >= 1000) discount = 10;
if (total >= 1000 && isMember) discount = 15;
console.log(total - total * discount / 100);

At 800 there is no discount, so you pay 800.

const total = 800;
const isMember = false;
let discount = 0;
if (total >= 1000) discount = 10;
if (total >= 1000 && isMember) discount = 15;
console.log(total - total * discount / 100);
Good to know

When you are unsure about a result, do not guess. Type the expression into the console and look. Experimenting costs nothing and teaches faster than reading.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What is 10 % 3?

  1. 3
  2. 1
  3. 0
  4. 3.33

10 divided by 3 is 3 remainder 1.

What does 5 === "5" return?

  1. true
  2. false
  3. error
  4. undefined

Strict equality also compares types.

What is 2 + 3 * 4?

  1. 20
  2. 14
  3. 24
  4. 9

Multiplication happens first.

Which operator means AND?

  1. ||
  2. &&
  3. !
  4. ==

&& needs both sides to be true.

What does "5" + 3 give?

  1. 8
  2. “53”
  3. 2
  4. error

With text on one side, + joins.

Summary

  • Arithmetic operators calculate, % gives the remainder.
  • Comparisons return true or false.
  • Use === for equality.
  • && || ! combine conditions.

Next lesson

Next: strings, working with text and template literals.

Questions

Why does 0.1 + 0.2 not equal 0.3?

Computers store decimals in binary, which cannot represent some fractions exactly. Round results when comparing money or measurements.

When is == acceptable?

Almost never. === avoids surprising conversions, so use it by default.

What is NaN?

It means Not a Number, the result of an impossible calculation like "abc" * 2.

Progress is saved in this browser.