Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The == (abstract equality) operator evaluates whether two operands are equal by applying the ECMAScript Abstract Equality Comparison algorithm. Unlike the strict equality operator (===), if the operands are of different data types, the JavaScript runtime implicitly converts (coerces) them to a common type before performing the comparison.

Type Coercion Mechanics

When evaluating x == y, the runtime applies the following primary coercion rules:
  • Null and Undefined: null and undefined are considered loosely equal to each other, but not to any other values.
  • String and Number: If one operand is a string and the other is a number, the string is converted to a number via the internal ToNumber operation.
  • Booleans: If either operand is a boolean, it is converted to a number (true becomes 1, false becomes 0) before further comparison.
  • BigInt: If a bigint is compared to a number, they are compared by their mathematical value without coercion. If a string is compared to a bigint, the string is converted to a bigint using the internal StringToBigInt operation.
  • Objects and Primitives: If one operand is an object and the other is a primitive (string, number, bigint, or symbol), the object is converted to a primitive using its internal ToPrimitive method (typically invoking valueOf() or toString()).

Syntax

operand1 == operand2

TypeScript Compiler Behavior

While TypeScript emits standard JavaScript == at runtime, its static type checker restricts abstract equality comparisons during compilation. If the TypeScript compiler determines that the types of the two operands have no overlap, it will throw a ts(2367) error, preventing the comparison of mutually exclusive types. To trigger runtime coercion in TypeScript without compiler errors, at least one operand must be typed as any or unknown, or the types must share a union.
let num: number = 5;
let str: string = "5";
let anyVal: any = "5";

// Runtime coercion (Allowed via 'any' type bypass)
console.log(num == anyVal); // Evaluates to true: "5" is coerced to 5

// Compile-time error
// TS2367: This condition will always return 'false' since the types 'number' and 'string' have no overlap.
// @ts-expect-error
console.log(num == str); 

Evaluation Order

  1. If the operand types are identical, the operator performs a strict equality comparison (identical to ===).
  2. If the operand types differ, the runtime attempts type coercion based on the ECMAScript specification.
  3. The newly coerced values are compared.
  4. The expression resolves to a boolean (true or false).
Master TypeScript with Deep Grasping Methodology!Learn More