为什么函数默认返回`undefined`而不是`null`? [英] Why do functions return `undefined` instead of `null` by default?
问题描述
为什么JavaScript函数默认返回 undefined
而不是 null
?这是规范完全武断的选择,还是有一个更大的ECMAScript行为上下文,可以理解这个特定的选择?
Why do JavaScript functions return undefined
by default instead of null
? Is this a totally arbitrary choice by the specification, or is there a larger ECMAScript-behavior context in which this particular choice can be understood?
function a() {}
a();
// undefined
null之间有什么区别
和 undefined
?是否存在基于规范的原因 undefined
更适合作为默认返回值,还是任意选择?
What is the difference between null
and undefined
? Is there a specification-based reason why is undefined
more appropriate as a default return value, or was it an arbitrary choice?
推荐答案
The specification says of null
and undefined
:
未定义值
未为变量赋值时使用的原始值
primitive value used when a variable has not been assigned a value
空值
表示故意缺少任何对象值的原始值
primitive value that represents the intentional absence of any object value
undefined
表示无法分配值。这是一个值的完全缺席。 null
表示对象上下文中非值的肯定断言。 null
旨在在预期对象但当前值为无对象时使用。
undefined
represents a failure to assign a value. It is the total absence of a value. null
represents the positive assertion of a non-value in an object context. null
is intended to be used when an object is expected but the current value is no-object.
鉴于这两个定义,很明显 undefined
是正确的选择,因为
Given these two definitions, it seems obvious that undefined
is the correct choice, since
- 函数可以返回除对象以外的值,并且
- 未能指定返回值整齐地映射到无法分配值
这篇关于为什么函数默认返回`undefined`而不是`null`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!