Lesson 3 of 12

JavaScript Operators

Once you have values stored in variables, you will want to do something with them: add prices, check whether a password is long enough, or decide which message to show. Operators are the symbols that do this work. Most JavaScript operators will look familiar from school maths, but a few have language-specific behaviour that every beginner should understand.

Arithmetic operators

OperatorMeaningExampleResult
+Addition8 + 311
-Subtraction8 - 35
*Multiplication8 * 324
/Division8 / 32.666…
%Remainder8 % 32
**Exponent (power)2 ** 532

The remainder operator % is more useful than it looks. n % 2 === 0 tells you whether a number is even, which is handy for striped table rows or alternating layouts. Note that dividing by zero does not crash: it gives Infinity, and invalid maths such as 'abc' * 2 gives NaN (“Not a Number”).

Among JavaScript operators, + has a second job: when either side is a string, it joins (concatenates) the values instead of adding them. That is why 'Rs. ' + 50 gives 'Rs. 50', and why '10' + 5 gives '105'. The other arithmetic operators always try to convert to numbers, so '10' - 5 is 5. This inconsistency is a common source of bugs – convert input with Number() first.

Assignment operators

The single = means “store this value”, not “is equal to”. Shortcut forms combine an operation with assignment:

  • total += 50 is short for total = total + 50
  • stock -= 1, price *= 2, amount /= 4 work the same way
  • count++ adds 1 and count-- subtracts 1
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Arithmetic</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
  </style>
</head>
<body>
  <pre id="out"></pre>

  <script>
let total = 0;
total += 120;      // samosa plate
total += 2 * 40;   // two masala chai
const gst = total * 5 / 100;
let items = 3;      // one plate + two cups
items++;           // added a sweet

const n = 17;
const isEven = n % 2 === 0;

document.getElementById('out').textContent =
`Subtotal: Rs. ${total}
GST (5%): Rs. ${gst}
Items: ${items}
2 ** 10 = ${2 ** 10}
Is ${n} even? ${isEven}
'10' + 5 = ${'10' + 5}
'10' - 5 = ${'10' - 5}`;
  </script>
</body>
</html>

Comparison operators

Comparisons always produce a boolean: true or false. You will use them constantly in conditions.

OperatorMeaning
===Strictly equal (same value and same type)
!==Strictly not equal
> <Greater than, less than
>= <=Greater than or equal, less than or equal
== !=Loose equality – converts types first (avoid)

Why === instead of ==

The loose operator == quietly converts values before comparing them, and the conversion rules are hard to remember. 0 == '' is true, '1' == 1 is true, and null == undefined is true. The strict operator === does no conversion: if the types differ, the answer is simply false. Code that uses === does what it says, so make it your default.

Logical operators

  • && (AND) – true only if both sides are true: age >= 18 && hasLicence
  • || (OR) – true if at least one side is true: isAdmin || isEditor
  • ! (NOT) – flips a boolean: !isLoggedIn

These operators also work with non-boolean values, and they return one of the original values rather than true or false. || returns the first “truthy” value, which is why you see it used for defaults. The problem is that 0 and an empty string are “falsy”, so a real quantity of 0 gets replaced. The newer nullish coalescing operator ?? only falls back when the left side is null or undefined, which is usually what you mean.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Comparison</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
  </style>
</head>
<body>
  <pre id="out"></pre>

  <script>
const age = 19;
const hasLicence = true;
const savedQty = 0;   // the user really chose zero

document.getElementById('out').textContent =
`'1' == 1   → ${'1' == 1}
'1' === 1  → ${'1' === 1}
0 == ''    → ${0 == ''}
0 === ''   → ${0 === ''}

Can drive? ${age >= 18 && hasLicence}
Not logged in? ${!true}

savedQty || 1 → ${savedQty || 1}   (zero was lost)
savedQty ?? 1 → ${savedQty ?? 1}   (zero kept)`;
  </script>
</body>
</html>

Precedence of JavaScript operators

When an expression has several operators, JavaScript follows precedence rules, just like maths: * and / run before + and -, comparisons run before &&, and && runs before ||. So 2 + 3 * 4 is 14, not 20. You do not need to memorise the full table – when in doubt, add parentheses. (2 + 3) * 4 is clear to both the engine and the next person who reads your code.

Watch out: Writing if (score = 100) instead of if (score === 100) is a classic mistake. The single = assigns 100 to score, and the condition is always true. Read = aloud as “becomes” and === as “is equal to” to train your eye.

Tip: There is also a conditional (ternary) operator, condition ? valueIfTrue : valueIfFalse. It is covered in the next lesson, JavaScript Conditions, together with if and switch.

Further reading

Key takeaways

  • Arithmetic: + - * / % ** ; % gives the remainder and is useful for even/odd checks.
  • + joins strings when either side is text – convert input with Number() first.
  • Shortcuts like += and ++ update a variable in place.
  • Always compare with === and !==; == converts types and causes surprises.
  • &&, || and ! combine conditions; ?? gives a default only for null or undefined.
  • Use parentheses to make precedence obvious.

Quick quiz

Check what you learned – pick an answer.

1. What is the value of 17 % 5?

2. Which expression is true?

3. If qty is 0, what does qty ?? 10 return?

Practice exercise

A movie ticket costs Rs. 180 and the convenience fee is Rs. 30 per booking. Calculate the total for 4 tickets in one booking, then show on the page whether the total is greater than Rs. 700 and whether the number of tickets is even.

Show a hint

Use parentheses or rely on * running before +. Use % 2 === 0 for the even check.

Show the solution
<pre id="out"></pre>
<script>
  const ticketPrice = 180;
  const fee = 30;
  const tickets = 4;
  const total = ticketPrice * tickets + fee;

  document.getElementById('out').textContent =
    `Total: Rs. ${total}
More than 700? ${total > 700}
Even number of tickets? ${tickets % 2 === 0}`;
</script>

Progress is saved in this browser only.