Thuta Learning
JavaScript
BasicProgrammingBeginner

JS Operators

JavaScriptLesson 625 min

What you'll walk away with

  • Calculate with arithmetic and assignment operators, including %, **, += and ++
  • Predict when + adds and when it joins strings
  • Explain the type conversion inside == and use === and !== by default
  • Write decisions and defaults with &&, ||, ?? and the conditional (? :) operator

Explain it simply

Explain it simply

Operators are the small symbols that take values and produce a new value. Just as a calculator has +, -, x and ÷ keys, JavaScript has operators to calculate (+ - * /), to compare (> < ===) and to combine decisions with "and" and "or" (&& ||).

Unlike a calculator, JavaScript operators also accept mixed types and do something instead of showing an error: "5" + 5 is "55", not 10. Most of this lesson is about knowing those surprises in advance.

Problem → Why → Solution

The problem: == hides a bug

A checkout page adds an item price of 10 to a shipping fee of "5" read from a form. The result is not 15 but "105". Worse, a check written as total == 105 passes, so the developer believes the value is fine. Only when the total feeds another calculation do the prices go haywire.

checkout.js
const price = 10;
const shipping = "5";              // came from a form field
const total = price + shipping;    // "105": + joined the text

console.log(total == 105);         // true  - hides the bug
console.log(total === 105);        // false - reveals it

Why does == say true?

== (loose equality) converts both sides to a common type before comparing, so the string "105" looks equal to the number 105. === (strict equality) converts nothing: values of different types are never equal. That is why === exposes the bug at once, while == carries it further into the program, where it does more damage.

Core concept: operands in, one value out

An operator takes one or two values, called operands, and produces a new value, so every piece of code with an operator is an expression. Unary operators such as ! and the minus in -x take one operand; binary operators such as + and === take two. The table shows the four groups you will use most.

GroupOperatorsExample → result
Arithmetic+ - * / % **17 % 5 → 2, 2 ** 3 → 8
Assignment= += -= *= ++ --total += 20 (100 → 120)
Comparison=== !== > < >= <=5 === "5" → false
Logical&& || !true && false → false

+ has two jobs: when both sides are numbers it adds, and when either side is a string it joins text. It works left to right, one step at a time, so 1 + 2 + "3" is "33" (first 3, then joined with "3"), while "1" + 2 + 3 is "123". % gives the remainder after division, which makes it the even/odd test (n % 2 === 0), and ** raises to a power.

== and != convert types before comparing, so 5 == "5", 0 == "" and null == undefined are all true. === and !== are true only when type and value both match, so use them every time. && and || short-circuit: && stops at the first falsy value and || at the first truthy one, and they return that operand itself rather than a boolean, which is why "" || "Guest" is "Guest". The conditional operator condition ? a : b gives a when the condition is true and b otherwise. By precedence, * and / run before + and -, and && before ||; when in doubt, add parentheses.

Mental model: reading an operator
  1. Operands in, one new value out
  2. + joins if either side is a string
  3. === checks type and value, no converting
  4. && / || stop early, return an operand

When unsure, add parentheses; when comparing, use ===.

General pattern

javascript
result = a + b;                 // arithmetic: + - * / % **
total += amount;                // assignment shortcut: += -= *= /=
a === b;   a !== b;             // strict comparison, no type conversion
a > b;     a <= b;              // relational comparison
x && y;    x || y;    !x;       // logical and, or, not
value ?? fallback;              // fallback only for null or undefined
condition ? ifTrue : ifFalse;   // conditional (ternary) operator

The values on either side of an operator are its operands. Shortcuts such as += are short for total = total + amount. The deeper section below compares ?? with ||.

Example: one line per operator group

This example prints x and y as well as the results, and gives each of the four operator groups its own line. Predict every line before you run it.

operators.js
let x = 5 + 5;        // 10
let y = "5" + 5;      // "55" (string joining)
let z = 5 == "5";     // true (loose equality converts types)
let a = 5 === "5";    // false (strict equality)

console.log(x, y);
console.log(z, a);
console.log(17 % 5, 2 ** 3);

let total = 100;
total += 20;
console.log(total);

const age = 20;
const hasTicket = false;
console.log(age >= 18 && hasTicket, age >= 18 || hasTicket, !hasTicket);

Code breakdown

  1. Line 2let y = "5" + 5; // "55" (string joining)

    One side is a string, so + turns the number 5 into the text "5" and joins them. console.log shows strings without quotes, so the output simply reads 55.

  2. Lines 3-4let a = 5 === "5"; // false (strict equality)

    == converts "5" to 5 and says true; === sees a number and a string, different types, and says false.

  3. Line 8console.log(17 % 5, 2 ** 3);

    5 goes into 17 three times with 2 left over, so 17 % 5 is 2. 2 ** 3 is 2 x 2 x 2 = 8.

  4. Line 11total += 20;

    Short for total = total + 20;. It reassigns total, which is why total is declared with let, not const.

  5. Line 16console.log(age >= 18 && hasTicket, age >= 18 || hasTicket, !hasTicket);

    age >= 18 is true. && needs both sides truthy, so it gives false; || needs only one, so it gives true; ! flips false into true.

You should see
10 55
true false
2 8
120
false true true

Short-circuit defaults and ??

|| is often used for default values, but it replaces every falsy value, including 0, "" and false. That wipes out meaningful values such as a volume of 0 or a deliberately empty name. ?? (nullish coalescing) replaces only null and undefined, so it keeps those values.

defaults.js
const savedName = "";
console.log(savedName || "Guest");           // Guest: "" is falsy
console.log("[" + (savedName ?? "Guest") + "]"); // []: "" is kept

const volume = 0;
console.log(volume || 50, volume ?? 50);     // 50 0

let count = 5;
count++;
console.log(count, 10 % 3, 2 + 3 * 4, (2 + 3) * 4); // 6 1 14 20

The last line shows precedence: in 2 + 3 * 4 the multiplication happens first and gives 14, and only the parentheses produce 20.

In real projects

Where this shows up in real projects

Every shopping cart computes its subtotal with * and +=. Pagination works out that 47 items at 10 per page need Math.ceil(47 / 10) = 5 pages, and striped tables colour every other row with index % 2. Checks such as user && user.isAdmin show a feature only to administrators. Game code leans on the same operators: score += points after each hit, lives-- when the player is caught, and level % 5 === 0 to start a boss round every fifth level.

In configuration code ?? matters: const timeout = options.timeout ?? 5000; keeps a deliberate timeout: 0, where || would silently replace it with 5000. Most teams enable ESLint's eqeqeq rule, so the editor flags every == and asks for === instead.

Common mistakes

Common mistakes

1. Using == and getting surprising trues

0 == "", "1" == true and null == undefined are all true. Rather than memorising these conversion rules, use only === and !==, and convert types yourself with Number() when needed.

2. Forgetting that + works left to right

"Total: " + 10 + 5 is "Total: 105", not "Total: 15": the string comes first, so every later + joins text. Add parentheses, "Total: " + (10 + 5), or write ${10 + 5} inside a template literal.

3. Using || for defaults when 0 or "" are valid

const quantity = input || 1; turns a typed 0 into 1. When only null and undefined should be replaced, use ?? instead.

4. Guessing precedence wrong

Writing a + b / 2 for an average divides only b by 2 and then adds a. Write (a + b) / 2.

Best practices

Best practices

  • Compare with === and !== every time; deliberate uses of == are rare.
  • Build text that mixes strings and numbers with template literals instead of +.
  • Add parentheses to any expression that mixes three or four operators, so the intent is obvious.

Mini challenge

Mini challenge: a checkout calculator

Work out a shop's checkout results using operators only, without any if statement.

  • subtotal = price * quantity (12.5 x 4)
  • Members with subtotal >= 40 get 10% off (use && and ? :)
  • Free shipping if subtotal >= 60 or the customer is a member (use ||)
  • Show "NONE" for an empty couponCode, and test whether quantity is even with %
checkout.js
const price = 12.5;
const quantity = 4;
const isMember = true;
const couponCode = "";

// TODO: subtotal
// TODO: getsDiscount - a member AND subtotal of at least 40
// TODO: total - 90% of subtotal when getsDiscount, otherwise subtotal
// TODO: freeShipping - subtotal of at least 60 OR a member
// TODO: code - couponCode, or "NONE" when it is empty

// TODO: print four lines: subtotal, discount + total,
//       free shipping + coupon, and whether quantity is even

Expected: Four lines are printed: Subtotal: 50 Discount: true Total: 45 Free shipping: true Coupon: NONE Even quantity: true

Show hint

Use the conditional operator: getsDiscount ? subtotal * 0.9 : subtotal. "" is falsy, so couponCode || "NONE" gives "NONE".

Show solution
checkout.js
const price = 12.5;
const quantity = 4;
const isMember = true;
const couponCode = "";

const subtotal = price * quantity;
const getsDiscount = isMember && subtotal >= 40;
const total = getsDiscount ? subtotal * 0.9 : subtotal;
const freeShipping = subtotal >= 60 || isMember;
const code = couponCode || "NONE";

console.log("Subtotal:", subtotal);
console.log("Discount:", getsDiscount, "Total:", total);
console.log("Free shipping:", freeShipping, "Coupon:", code);
console.log("Even quantity:", quantity % 2 === 0);

Quick quiz 1 / 3

What does console.log(1 + 2 + "3"); print?

Quick quiz 2 / 3

Which of these expressions is false?

Quick quiz 3 / 3

What does const volume = 0; console.log(volume || 50, volume ?? 50); print?

What to remember

  • Operators take operands and produce a new value: arithmetic, assignment, comparison and logical.
  • + joins text when either side is a string, and it works left to right.
  • == converts types before comparing, so always use === and !==.
  • && and || short-circuit and return an operand; use ?? when 0 or "" must survive.

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

JS Operators | Thuta Learning