Skip to main content
The != (loose inequality) operator evaluates to true if its two operands are not equal, performing automatic type coercion before comparison if the operands are of different types. It is the negated counterpart to the == (loose equality) operator and contrasts with the !== (strict inequality) operator, which does not perform type conversion.

Evaluation Mechanics

When evaluating operand1 != operand2, the JavaScript runtime underlying TypeScript applies the Abstract Equality Comparison algorithm. The mechanics are as follows:
  1. Identical Types: If both operands are of the same type, no coercion occurs. The operator behaves identically to !==.
  2. NaN Behavior: The NaN (Not-a-Number) value is never equal to any value, including itself. Therefore, NaN != NaN always evaluates to true.
  3. Nullish Operands: null and undefined are considered loosely equal to each other, but not to any other values. Therefore, null != undefined evaluates to false. Comparing any object to null or undefined evaluates to true without triggering any type conversion.
  4. Primitive Coercion: If comparing a number and a string, the runtime attempts to convert the string to a number before evaluating inequality.
  5. Boolean Coercion: If one operand is a boolean, it is converted to a number (true becomes 1, false becomes 0) before comparison.
  6. Object to Primitive: If one operand is an object and the other is a string, number, bigint, or symbol, the object is converted to a primitive value via its valueOf() or toString() methods before comparison.

TypeScript Static Analysis Behavior

While TypeScript inherits the runtime behavior of != from JavaScript, its static type checker restricts how the operator can be written. TypeScript prevents the comparison of mutually exclusive types, throwing a TS2367 error, as such comparisons are logically flawed in a strongly typed environment.
To observe the loose inequality coercion mechanics without triggering a compiler error, the operands must generally have overlapping types, or at least one operand must be typed as any or unknown. However, the TypeScript compiler implements a specific, built-in exception for nullish values: it explicitly permits loose inequality comparisons between the distinct null and undefined types. This exception allows developers to check for both values simultaneously without throwing the TS2367 (no overlap) error, even under strict type-checking.

Memory Reference Comparison

When both operands are objects (including arrays and functions), the != operator does not compare their internal structures or values. Instead, it compares their memory references. It evaluates to true if the operands point to different locations in memory, regardless of whether their contents are identical.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More