Operators in JavaScript

By Syncfusion®, Inc. · Last updated

Arithmetic, assignment, comparison, logical, unary and ternary operators, and the precedence rules that decide which operator runs first.

What Is an Operator?

Operator = a symbol that does a job with values.

  • + adds: 249 + 100 gives 349.
  • > compares: 349 > 300 gives true.
  • && combines: "signed in and cart not empty".

Simple lesson: operators turn values into new values: a total, a yes/no, or a choice.

A Real-World Example

At checkout the shop works out price * quantity + delivery. Then it checks total >= 499 to give free delivery. Then isSignedIn && total > 0 decides whether the Pay button works.

249 2

* 498

>= 499 false

Each operator takes values in and gives one value out.

Operators chain together: a maths answer becomes the input of a comparison.

Each box prints its answers in the Console. Change a number and run it again.

What You Will Learn

  1. Maths and assignment operators.
  2. Comparison operators, and why === beats ==.
  3. Logical operators &&, || and !.
  4. ++, --, typeof and the ternary ? :.
  5. Which operator runs first (precedence).

Arithmetic Operators (+, -, *, /, %, **)

OperatorMeaningExampleResult
+ -Add, subtract250 - 50200
* /Multiply, divide90 / 422.5
%Remainder10 % 31
**Power2 ** 38

Six arithmetic operators on a small order

const price = 90;
const quantity = 4;
console.log("Add:", price + 10);
console.log("Subtract:", price - 15);
console.log("Multiply:", price * quantity);
console.log("Divide:", price / quantity);
console.log("Remainder:", price % quantity);
console.log("Power:", quantity ** 2);

Expected output:

Add: 100
Subtract: 75
Multiply: 360
Divide: 22.5
Remainder: 2
Power: 16

The remainder operator %

% gives what is left over after dividing.

  • n % 2 === 0 means n is even.
  • items % boxSize is how many items do not fill a box.

Using % to find even numbers and to split items into boxes

console.log(8 % 2, 7 % 2);
const items = 14;
const boxSize = 6;
console.log("Full boxes:", Math.floor(items / boxSize));
console.log("Left over:", items % boxSize);

Expected output:

0 1
Full boxes: 2
Left over: 2

The exponent operator **

a ** b multiplies a by itself b times.

Savings that grow by 5 percent a year for 3 years

const savings = 1000;
const afterThreeYears = savings * 1.05 ** 3;
console.log(afterThreeYears.toFixed(2));

Expected output:

1157.63

Assignment Operators (=, +=, -=, *=, /=, %=)

total += 50 is short for total = total + 50. The others work the same way.

One running total, updated by each shorthand

let total = 200;
total += 50;
console.log("+= 50:", total);
total -= 30;
console.log("-= 30:", total);
total *= 2;
console.log("*= 2:", total);
total /= 4;
console.log("/= 4:", total);
total %= 100;
console.log("%= 100:", total);

Expected output:

+= 50: 250
-= 30: 220
*= 2: 440
/= 4: 110
%= 100: 10

Comparison Operators

Comparisons always give true or false.

OperatorMeaning
> < >= <=Bigger, smaller, or equal
=== !==Same value and same type (use these)
== !=Same after converting types (avoid)

Greater than and less than

Checking a cart total against a free delivery limit

const cartTotal = 499;
console.log(cartTotal > 499);
console.log(cartTotal >= 499);
console.log(cartTotal < 500);

Expected output:

false
true
true

Strict equality === and loose equality ==

== converts types first, so "5" == 5 is true. === does not.

The same comparisons, strict and loose

console.log("5" == 5, "5" === 5);
console.log(0 == "", 0 === "");
console.log(null == undefined, null === undefined);

Expected output:

true false
true false
true false

Not equal !== and !=

Checking that an order status is not cancelled

const status = "shipped";
console.log(status !== "cancelled");
console.log(status !== "shipped");

Expected output:

true
false

Logical Operators (&&, ||, !)

  • a && b: true only if both are true.
  • a || b: true if at least one is true.
  • !a: flips true and false.

Deciding whether a customer can check out

const isSignedIn = true;
const cartTotal = 0;
const hasCoupon = false;
console.log(isSignedIn && cartTotal > 0);
console.log(cartTotal > 0 || hasCoupon);
console.log(!hasCoupon);

Expected output:

false
false
true

Short-circuiting

JavaScript stops as soon as the answer is known. So && skips the right side when the left is false, and || skips it when the left is true.

The right side is skipped when the left side decides

const cart = [];
const firstItem = cart.length > 0 && cart[0].name;
console.log(firstItem);

const nickname = "" || "Guest";
console.log(nickname);

Expected output:

false
Guest

cart[0].name never ran, so there was no error on the empty cart.

Unary Operators (++, --, typeof)

Unary = works on one value.

Increment ++ and decrement --

++ adds 1. -- takes 1 away.

Counting items added to and removed from a cart

let items = 0;
items++;
items++;
items--;
console.log(items);

Expected output:

1

The position matters when you use the value in the same line:

  • count++ gives the old value, then adds.
  • ++count adds first, then gives the new value.

The position of ++ changes the value you get back

let views = 10;
console.log(views++);
console.log(views);
console.log(++views);

Expected output:

10
11
12

typeof

typeof gives the type as text. Use it to check a value before you use it.

typeof checks the type before the code uses a value

const quantity = "3";
if (typeof quantity === "string") {
  console.log("Converting", quantity, "to", Number(quantity));
}

Expected output:

Converting 3 to 3

Ternary Operator (? :)

condition ? valueIfTrue : valueIfFalse picks one of two values in one line.

Choosing a delivery message from the cart total

const total = 620;
const message = total >= 499 ? "Free delivery" : "Delivery ₹40";
console.log(message);

Expected output:

Free delivery

Operator Precedence ((), **, *, /, %, +, -)

Like school maths: brackets first, then **, then * / %, then + -.

The same numbers, different groupings, different answers

console.log(10 + 6 / 2);
console.log((10 + 6) / 2);
console.log(2 + 3 * 4 ** 2);

Expected output:

13
8
50

Forgetting brackets is a common bug:

An average written without brackets gives the wrong answer

const a = 60;
const b = 80;
console.log("Wrong:", a + b / 2);
console.log("Right:", (a + b) / 2);

Expected output:

Wrong: 100
Right: 70

Operators on a Web Page

The form gives text, so convert it with Number(). Then use maths, a comparison and a ternary. Change the quantity in the Preview and press Place order.

Working out an order total from a form

const PRICE = 149;
const FREE_DELIVERY_FROM = 499;
const form = document.querySelector("#order");
const qty = document.querySelector("#qty");
const result = document.querySelector("#result");

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const quantity = Number(qty.value);
  const subtotal = PRICE * quantity;
  const delivery = subtotal >= FREE_DELIVERY_FROM ? 0 : 40;
  const total = subtotal + delivery;
  result.textContent = `${quantity} × ₹${PRICE} + ₹${delivery} delivery = ₹${total}`;
  console.log("subtotal", subtotal, "free delivery?", delivery === 0);
});

Try a quantity of 4. The subtotal is ₹596, so delivery becomes ₹0.

Easy way to remember: always use three equals signs, ===. Add brackets whenever you are not sure.

TL;DR

  • Maths: + - * / % **. % is the remainder.
  • x += 5 means x = x + 5.
  • Use === and !==. == converts types and surprises you.
  • && both, || either, ! flips. They stop early.
  • cond ? a : b picks a value. Brackets run first.

Try this

Guess "3" * "4" and "3" + "4", then run them. You get 12 and "34": only + joins text.

Check Yourself

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
if (status = "paid")= compares= stores; === comparesThe condition is always true
"7" == 7It checks the type== converts firsttrue when you expected false
a + b / 2 for an averageLeft to right/ runs before +Wrong average
console.log(count++)It prints the new valuecount++ gives the old valueOff by one
qty.value + 1Input values are numbersThey are strings; use Number(qty.value)"21" instead of 3 for a value of 2

Quick reference

SyntaxMeaning
a + b, a - b, a * b, a / badd, subtract, multiply, divide
a % bthe remainder after dividing a by b
a ** ba to the power of b
x = valuestore a value in x
x += n, x -= n, x *= n, x /= n, x %= nupdate x from its own value
a === b, a !== bstrictly equal, strictly not equal
a == b, a != bequal or not equal after converting types
a > b, a < b, a >= b, a <= bordering comparisons
a && b, `ab, !a`AND, OR, NOT
x++, x--add 1, subtract 1
typeof xthe type of x, as a string
condition ? a : ba when the condition is true, otherwise b
( )run this part first

Exercises

What to Remember

  • Operators take values and give a new value.
  • === for equality, brackets for clear order.
  • Convert text from forms with Number() before maths.

Next: Conditional Statements. Use these true/false answers to choose what code runs.