# Operators

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Basics
Source: https://www.devtutorials.ai/learn/javascript/basics/operators

> 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.

<figure className="ts-fig">
  <svg viewBox="0 0 560 160" role="img" aria-label="Two values flow into an operator box and a result comes out: 249 times 2 gives 498, then 498 greater than or equal to 499 gives false." width="100%">
    <rect x="0" y="0" width="560" height="160" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <text x="40" y="55" fontSize="16" fontFamily="monospace" fill="#1e40af">249</text>
    <text x="40" y="95" fontSize="16" fontFamily="monospace" fill="#1e40af">2</text>
    <rect x="130" y="45" width="80" height="44" rx="22" fill="#2563eb" />
    <text x="170" y="73" textAnchor="middle" fontSize="18" fill="#ffffff">*</text>
    <text x="250" y="73" fontSize="16" fontFamily="monospace" fill="#1e40af">498</text>
    <rect x="320" y="45" width="80" height="44" rx="22" fill="#ca8a04" />
    <text x="360" y="73" textAnchor="middle" fontSize="15" fill="#ffffff">&gt;= 499</text>
    <text x="440" y="73" fontSize="16" fontFamily="monospace" fill="#b91c1c">false</text>
    <circle r="6" cx="90" cy="68" fill="#2563eb">
      <animate attributeName="cx" values="90;130;250;320;440" keyTimes="0;0.2;0.45;0.65;1" dur="3.5s" repeatCount="indefinite" />
    </circle>
    <text x="280" y="135" textAnchor="middle" fontSize="12" fill="#475569">Each operator takes values in and gives one value out.</text>
  </svg>
  <figcaption>Operators chain together: a maths answer becomes the input of a comparison.</figcaption>
</figure>

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 (+, -, *, /, %, **)

| Operator | Meaning | Example | Result |
|---|---|---|---|
| `+` `-` | Add, subtract | `250 - 50` | `200` |
| `*` `/` | Multiply, divide | `90 / 4` | `22.5` |
| `%` | Remainder | `10 % 3` | `1` |
| `**` | Power | `2 ** 3` | `8` |

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
0 1
Full boxes: 2
Left over: 2
```

### The exponent operator `**`

`a ** b` multiplies `a` by itself `b` times.

```js runnable title="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:

```text
1157.63
```

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

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

```js runnable title="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:

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

## Comparison Operators

Comparisons always give `true` or `false`.

| Operator | Meaning |
|---|---|
| `>` `<` `>=` `<=` | Bigger, smaller, or equal |
| `===` `!==` | Same value **and** same type (use these) |
| `==` `!=` | Same after converting types (avoid) |

### Greater than and less than

```js runnable title="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:

```text
false
true
true
```

### Strict equality `===` and loose equality `==`

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

```js runnable title="The same comparisons, strict and loose"
console.log("5" == 5, "5" === 5);
console.log(0 == "", 0 === "");
console.log(null == undefined, null === undefined);
```

Expected output:

```text
true false
true false
true false
```

### Not equal `!==` and `!=`

```js runnable title="Checking that an order status is not cancelled"
const status = "shipped";
console.log(status !== "cancelled");
console.log(status !== "shipped");
```

Expected output:

```text
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.

```js runnable title="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:

```text
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.

```js runnable title="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:

```text
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.

```js runnable title="Counting items added to and removed from a cart"
let items = 0;
items++;
items++;
items--;
console.log(items);
```

Expected output:

```text
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.

```js runnable title="The position of ++ changes the value you get back"
let views = 10;
console.log(views++);
console.log(views);
console.log(++views);
```

Expected output:

```text
10
11
12
```

### `typeof`

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

```js runnable title="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:

```text
Converting 3 to 3
```

## Ternary Operator (? :)

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

```js runnable title="Choosing a delivery message from the cart total"
const total = 620;
const message = total >= 499 ? "Free delivery" : "Delivery ₹40";
console.log(message);
```

Expected output:

```text
Free delivery
```

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

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

```js runnable title="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:

```text
13
8
50
```

Forgetting brackets is a common bug:

```js runnable title="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:

```text
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**.

```js runnable preview="order-form" title="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

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `if (status = "paid")` | `=` compares | `=` stores; `===` compares | The condition is always true |
| `"7" == 7` | It checks the type | `==` converts first | `true` when you expected `false` |
| `a + b / 2` for an average | Left to right | `/` runs before `+` | Wrong average |
| `console.log(count++)` | It prints the new value | `count++` gives the old value | Off by one |
| `qty.value + 1` | Input values are numbers | They are strings; use `Number(qty.value)` | `"21"` instead of `3` for a value of 2 |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `a + b`, `a - b`, `a * b`, `a / b` | add, subtract, multiply, divide |
| `a % b` | the remainder after dividing `a` by `b` |
| `a ** b` | `a` to the power of `b` |
| `x = value` | store a value in `x` |
| `x += n`, `x -= n`, `x *= n`, `x /= n`, `x %= n` | update `x` from its own value |
| `a === b`, `a !== b` | strictly equal, strictly not equal |
| `a == b`, `a != b` | equal or not equal after converting types |
| `a > b`, `a < b`, `a >= b`, `a <= b` | ordering comparisons |
| `a && b`, `a || b`, `!a` | AND, OR, NOT |
| `x++`, `x--` | add 1, subtract 1 |
| `typeof x` | the type of `x`, as a string |
| `condition ? a : b` | `a` when the condition is true, otherwise `b` |
| `( )` | run this part first |

</div>

## 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.
