JS Operators
JavaScript operators do arithmetic, compare values, combine booleans, and assign. Knowing the categories makes the precedence rules feel natural.
Operator categories
| Category | Operators | Example |
|---|---|---|
| Arithmetic | + - * / % ** ++ -- | 2 ** 8 → 256 |
| Assignment | = += -= *= /= %= **= ??= | count += 1 |
| Comparison | == === != !== < > <= >= | "5" === 5 → false |
| Logical | && || ! ?? | name ?? "anon" |
| String | + (concat) | "Hi, " + name |
| Bitwise | & | ^ ~ << >> >>> | 0b1100 & 0b1010 |
| Ternary | ? : | ok ? "yes" : "no" |
| Type | typeof, instanceof, in | "id" in obj |
| Spread / rest | ... | [...arr] |
The + trap
JS
1 + 2 // 3 — numbers "1" + 2 // "12" — string wins as soon as one side is a string 1 + "2" + 3 // "123" — left-to-right 1 - "2" // -1 — minus forces numeric
Tip: Always use
=== and !== for equality. The loose versions (==) silently coerce types, which is the source of more bugs than it solves.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Operators!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Use the operator that compares values WITHOUT type coercion.
if (a
b) { /* same type and value */ }
Three equals signs.
Discussion
Loading…