JavaScript Operators: Special Cases and Type Coercion

JavaScript operators share many similarities with those in Java, but several exhibit unique behaviors speicfic to the language's dynamic typing.

Division and Modulus with / and %

In JavaScript, the number type encompasses both integers and floats. The division operator (/) yields an integer result only if the division is exact; otherwise, it produces a floating-point number. Dividing by zero does not throw an error but returns Infinity. The modulus operator (%) also works with floating-point numbers. Performing a modulus operation with zero results in NaN (Not a Number).

console.log(10 / 3);   // Output: 3.3333333333333335
console.log(10 / 0);   // Output: Infinity
console.log(10 % 3);   // Output: 1
console.log(10 % 0);   // Output: NaN
console.log(10.5 % 3); // Output: 1.5

The Addition Operator +

The + operator serves dual purposes. It performs arithmetic addition when both operands are numbers. If one operand is a string, it acts as a concatenation operator, converting the other operand to a string. When a boolean is added to a number, true converts to 1 and false converts to 0 before the operation proceeds.

let value = 5;
console.log(value + 2);        // Output: 7 (addition)
console.log(3 + "5");          // Output: "35" (concatenation)
console.log(4 + true);         // Output: 5 (true -> 1)
console.log(4 + false);        // Output: 4 (false -> 0)
console.log("Result: " + 10);  // Output: "Result: 10"

Loose Equality == (Abstract Equality)

The loose equality operator (==) performs type coercion before comparison. If the operands are of the same type, it compares their values directly. If the types differ, JavaScript attempts to convert them to numbers, then compares the resulting values.

let num = 1;
let strNum = "1";
let boolTrue = true;
let strTrue = "true";

console.log(num == strNum);    // Output: true ("1" -> 1)
console.log(num == boolTrue);  // Output: true (true -> 1)
console.log(num == strTrue);   // Output: false ("true" -> NaN)
console.log(strNum == boolTrue); // Output: true (both coerce to 1)
console.log(strNum == strTrue);  // Output: false
console.log(boolTrue == strTrue);// Output: false

Strict Equality === (Identity)

The strict equality operator (===) does not perform type conversion. It returns false immediately if the operends are of different types. Only if the types are identical does it proceed to compare the values.

let x = 1;
let y = "1";
let z = true;
let w = "true";

console.log(x === y);   // Output: false (number vs string)
console.log(x === z);   // Output: false (number vs boolean)
console.log(x === w);   // Output: false
console.log(y === z);   // Output: false (string vs boolean)
console.log(y === w);   // Output: false
console.log(z === w);   // Output: false
console.log("text" === "text"); // Output: true (same type and value)

Tags: javascript Operators type-coercion equality arithmetic

Posted on Thu, 28 May 2026 20:39:03 +0000 by BLottman