Test NaN Equality

ID

javascript.test_nan_equality

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

JavaScript

Tags

CWE:597, reliability, suspicious-comparison

Description

Reports equality comparisons against NaN or Number.NaN using ==, !=, ===, or !==. By the IEEE 754 specification implemented by JavaScript numbers, NaN is not equal to anything — including itself — so the comparison is always false (or always true for the negated form).

Rationale

x === NaN is always false, regardless of x. The branch never runs, the bug hides, and the actual NaN check the developer intended is missing.

// Bad - always false
if (result === NaN) { ... }
if (value !== Number.NaN) { ... }

Remediation

Use Number.isNaN(x) (preferred) or the global isNaN(x) — note that the global isNaN returns true for any value that would coerce to NaN (e.g. the string "foo"), while Number.isNaN returns true only for actual NaN.

// Good
if (Number.isNaN(result)) { ... }