JavaScript Operators

Maths, assignment shortcuts, comparisons and logic with &&, || and !.

Lesson 6 of 56Beginner13 min read

Operators are the symbols that do work on values: + adds, > compares and && combines two conditions. You've used some of them since primary school maths, and a few are new and very useful.

Operators appear in almost every line of real code. Updating a score, checking whether a password is long enough and deciding which message to show all rely on them. This lesson gives you an overview of each group, and later lessons go deeper into comparisons and conditions.

Arithmetic operators

OperatorMeaningExampleResult
+Add7 + 29
-Subtract7 - 25
*Multiply7 * 214
/Divide7 / 23.5
%Remainder (modulo)7 % 21
**Power7 ** 249

The usual maths order applies: * and / happen before + and -. Use brackets to make your intention clear, as in (2 + 3) * 4.

Be careful with +: when either side is a string, it joins text instead of adding numbers, so "2" + 3 gives "23".

Assignment shortcuts

WriteSame as
x += 5x = x + 5
x -= 5x = x - 5
x *= 2x = x * 2
x++x = x + 1
x--x = x - 1

These shortcuts appear constantly in counters, scores and running totals.

Comparison operators

=== (equal), !== (not equal), >, <, >= and <= all return true or false. Always use triple equals, ===. The double version, ==, converts types in confusing ways, so "1" == 1 is true. More in Comparisons.

Logical operators

  • && (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.
  • ?? (nullish coalescing) uses the right side only when the left is null or undefined, as in nickname ?? "Guest".

Logical operators let you combine simple checks into real rules, such as "the basket isn't empty and the visitor has entered an address".

The ternary operator

The ternary operator is a one-line if/else: condition ? valueIfTrue : valueIfFalse.

JavaScript
const label = age >= 18 ? "adult" : "minor";

It's ideal for choosing between two values. For anything longer, a normal if...else statement is easier to read.

JavaScript Operators Syntax

Operators at a glance

let total = (price + tax) * qty;
total += 5;
count++;
const isAdult = age >= 18;
const canEnter = hasTicket && !isBanned;
const name = input ?? "Guest";
const msg = score > 50 ? "Pass" : "Try again";

JavaScript Operators Summary

  • Arithmetic operators do maths; % gives the remainder of a division.
  • Shortcuts like += and ++ update a variable in place.
  • Always compare with === and !==.
  • &&, || and ! combine and flip true/false values; ?? supplies a default.
  • The ternary operator chooses between two values in one line.

JavaScript Operators Examples

Each example runs in the page. Edit the code and press Run to see what changes.

Example 1

Maths in action

const minutes = 135;

const hours = Math.floor(minutes / 60);
const leftover = minutes % 60;

console.log(hours, "h", leftover, "min");
console.log("2 to the power 10 =", 2 ** 10);
console.log("Is 17 even?", 17 % 2 === 0);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 3Divide and round down to get whole hours: 2.
  2. Line 4The remainder gives the leftover minutes: 15.
  3. Line 7** raises to a power.
  4. Line 8A number is even if dividing by 2 leaves no remainder.
Example 2

A score counter

let score = 0;

score += 10; // collected a coin
score += 10;
score *= 2;  // double points power-up!
score--;     // tiny penalty

console.log("Final score:", score);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Lines 3 to 4+= adds to the current value.
  2. Line 5*= multiplies the current value: 20 × 2 = 40.
  3. Line 6-- subtracts one: 39.
Example 3

Logic for a cinema ticket

const age = 15;
const withAdult = true;
const nickname = null;

const canWatch = age >= 15 || withAdult;
const needsId = age < 18 && !withAdult;
const greeting = "Enjoy the film, " + (nickname ?? "movie fan") + "!";
const ticket = age < 16 ? "Child £6" : "Adult £10";

console.log(canWatch, needsId);
console.log(greeting);
console.log(ticket);
ConsoleEdit the code, then press Run or Ctrl+Enter
Line-by-line explanation
  1. Line 5OR: true if old enough or with an adult.
  2. Line 6AND + NOT: under 18 and not with an adult.
  3. Line 7?? falls back to "movie fan" because nickname is null.
  4. Line 8Ternary picks one of two values.

Common JavaScript Operators Mistakes

Using = instead of ===

Don't
if (score = 100) { … } // assigns 100, always true!
Do
if (score === 100) { … }

A single = assigns. Comparisons need ===.

Using || for defaults when 0 is valid

Don't
const volume = settings.volume || 50; // volume 0 becomes 50!
Do
const volume = settings.volume ?? 50; // only null/undefined use 50

|| treats 0 and "" as "missing". ?? only falls back for null and undefined.

JavaScript Operators in Real Projects

Operators in everyday code

Shopping carts use += for totals and * for quantities, games use % for repeating patterns and ++ for scores, forms use && to check every field is valid, and nearly every interface uses the ternary operator to pick labels like "1 item" vs "2 items".

JavaScript Operators Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Add 5 to the score, then check if it's at least 20.

let score = 15;
score  5;
const passed = score  20;
console.log(passed);
Predict the outputeasy

What does this print?

console.log(10 % 3);
console.log(2 + 3 * 4);
Predict the outputmedium

What does this print?

const a = 0 || "default";
const b = 0 ?? "default";
console.log(a, b);
Fix the bugmedium

The program should log Delivery included: true when the cart total is at least 50 and the user is a member. Fix the operators.

const cartTotal = 60;
const isMember = true;
const deliveryIncluded = cartTotal => 50 & isMember;
console.log("Delivery included:", deliveryIncluded);
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Delivery included: true"
  • deliveryIncluded is a boolean

JavaScript Operators Quiz

4 questions to check what you learned.

  1. What does x++ do?

    • Doubles x
    • Adds 1 to x
    • Adds x to itself
    • Nothing
  2. What is true && false?

    • false
    • true
    • undefined
    • An error
  3. What does const msg = 7 > 5 ? "yes" : "no"; store?

    • "no"
    • true
    • "yes"
    • 7
  4. What is "2" * "3"?

    • "23"
    • "6"
    • NaN
    • 6

JavaScript Operators Challenge

Pizza party maths

You have the variables below. Calculate and log:

  1. const total = pizzas * slicesPerPizza; → log Slices: 24
  2. const each = Math.floor(total / people); → log Each: 3
  3. const spare = total % people; → log Spare: 3
  4. const enough = each >= 3 ? "Yes" : "No"; → log Enough? Yes
const pizzas = 3;
const slicesPerPizza = 8;
const people = 7;
ConsoleEdit the code, then press Run or Ctrl+Enter
Checks
  • Logs "Slices: 24"
  • Logs "Each: 3"
  • Logs "Spare: 3"
  • Logs "Enough? Yes"
  • spare uses the % operator correctly