Loose Equality Coerces Before Comparing
== converts both sides before comparing so strings, arrays and booleans can equal numbers, while === never converts and Object.is alone finds NaN.
Code
// == 先做类型转换再比较;=== 不转换,类型不同直接 false
console.log("'1' == 1 :", '1' == 1, "| '1' === 1 :", '1' === 1);
console.log('0 == false :', 0 == false, '| 0 === false :', 0 === false);
console.log("'' == 0 :", '' == 0, "| '' === 0 :", '' === 0);
console.log('null == undefined :', null == undefined, '| === :', null === undefined);
console.log('[1] == 1 :', [1] == 1, '| [1] === 1 :', [1] === 1);
// NaN 与谁都不相等,包括它自己;Object.is 是唯一认它的比较
console.log('NaN == NaN :', NaN == NaN, '| Object.is :', Object.is(NaN, NaN));
// +0 与 -0 在 == 和 === 里相等,Object.is 能区分
console.log('0 == -0 :', 0 == -0, '| Object.is :', Object.is(0, -0));
// null 只与 undefined 宽松相等:其它真值比较都走数字转换
console.log('null == 0 :', null == 0, '| null >= 0 :', null >= 0);
// 现代代码默认 === / !==:把 == 留给 null == x 这种判空惯用法
const maybeNull = null;
console.log('idempotent check :', maybeNull == null, '(null == null)');Output
Captured from a sandboxed run of this snippet in the build pipeline.
'1' == 1 : true | '1' === 1 : false
0 == false : true | 0 === false : false
'' == 0 : true | '' === 0 : false
null == undefined : true | === : false
[1] == 1 : true | [1] === 1 : false
NaN == NaN : false | Object.is : true
0 == -0 : true | Object.is : false
null == 0 : false | null >= 0 : true
idempotent check : true (null == null)What the code does
Everything operates on top-level bindings: maybeNull.
Points of care
- It is dependency-free in the strict sense — the import list, if any, is empty of packages.
Using it
Expect labeled output — 0 == false :, null == undefined :, [1] == 1 : — when the file runs.
Key statements
const maybeNull = null;
Interactive Tools for This Topic
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `maybeNull`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.