Null And Undefined Are Distinct Absences

null is an explicitly assigned empty value while undefined marks missing values; === tells them apart even though == and default parameters collapse them.

JavascriptData Integrity

Code

javascriptsnippet
21 lines
// undefined:声明了还没赋值,或者访问了不存在的属性
let assigned;
console.log('assigned:', assigned, '| typeof:', typeof assigned);

// null:程序显式写入的空值;typeof null 是历史遗留的 "object"
const current = null;
console.log('current:', current, '| typeof null:', typeof null);

// == 把两者视为等价,=== 区分;写空值判断时用 ===
console.log('null == undefined:', null == undefined);
console.log('null === undefined:', null === undefined);

// 默认参数只在收到 undefined 时生效:null 会原样传入
function greet(name, greeting = 'hello') {
  console.log(greeting, name);
}
greet('ada', undefined);
greet('ada', null);

// 数字转换的结果不同:Number(null) 是 0,Number(undefined) 是 NaN
console.log('Number(null):', Number(null), '| Number(undefined):', Number(undefined));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

assigned: undefined | typeof: undefined
current: null | typeof null: object
null == undefined: true
null === undefined: false
hello ada
null ada
Number(null): 0 | Number(undefined): NaN

How the snippet works

Null And Undefined Are Distinct Absences keeps everything in the function greet.

Applying it

Entry signature: function greet(name, greeting = 'hello')

The demo output is labeled (assigned:, current:, null == undefined:), so every printed line maps back to its originating operation.

Statements that matter

greet('ada', undefined);
const current = null;
greet('ada', null);

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `greet` at load time.