JavaScript Operators: Arithmetic, === and Logical
Operators combine values into new values. Most look familiar from maths, but JavaScript's automatic type conversion gives a few of them behavior you need to know about.
Arithmetic and the two faces of +
+ - * / work as expected, % gives the remainder, and ** raises to a power. Division always produces a decimal when needed: 7 / 2 is 3.5.
+ has a second job: if either side is a string, it concatenates. So "5" + 3 is the string "53". The other arithmetic operators only do maths, so "5" - 3 converts the string and gives 2. When adding values that might be strings, convert them with Number() first.
Strict and loose equality
=== (strict equality) is true only when both values have the same type and value. == (loose equality) first converts the values to a common type, which leads to results like 1 == "1" being true. Always use === and !==. The one widely accepted use of == is x == null, which matches both null and undefined.
NaN is not equal to anything, including itself, so test for it with Number.isNaN().
Expected output
1 1024 3.5 53 2 10 true false true false false true yes default fallback 0 12
Logical operators return values
&& and || do not just return true or false; they return one of their operands, and they short-circuit:
a && breturnsaif it is falsy, otherwiseb.a || breturnsaif it is truthy, otherwiseb. That makes it a common way to supply defaults.a ?? b(nullish coalescing) returnsbonly whenaisnullorundefined.
The difference between || and ?? matters for legitimate falsy values. In the example, 0 || "default" replaces the zero, while 0 ?? "kept" keeps it. For a quantity or a price, ?? is usually what you want.
The falsy values are false, 0, -0, 0n, "", null, undefined and NaN. Everything else, including "0", [] and {}, is truthy.
Assignment shortcuts
count++ adds one, count-- subtracts one, and compound operators like +=, *= and ??= update a variable in place.
Common mistakes
- Using
==and getting surprised by conversions such as"" == 0beingtrue. - Using
||for defaults when0or""are valid values. - Comparing with
NaNusing===.
Summary
+concatenates when either side is a string; other operators convert to numbers.- Use
===and!==; loose==converts types. &&,||and??return operands and short-circuit;??only replacesnullandundefined.
Quiz: Operators and equality