I have a function which I have written which basically looks like this:
我有一个我写的功能,基本上看起来像这样:
function getNextCard(searchTerms) {
// Setup Some Variables
// Do a bunch of logic to pick the next card based on termed passed through what I'll call here as 'searchTerms' all of this logic is omitted because it's not important for my question.
// ...
// If we find a next card to give, than give it
if (nextCardFound)
return nextCardFound;
// Otherwise - I'm returning undefined
return undefined;
}
Question: Would it be better to return "null" here?
问题:在这里返回“null”会更好吗?
I can pass whatever I want back - obviously... I just wasn't sure what is the best thing to use.
我可以通过我想要的任何东西 - 显然......我只是不确定什么是最好用的。
The code that calls this function knows how to deal with undefined (it actually won't ever really happen unless something goes horribly wrong)
调用此函数的代码知道如何处理未定义的(除非发生可怕的错误,否则实际上不会真正发生)
The reason I'm asking this question is that I heard somewhere something that sounded like "Don't assign undefined to variables" or something - that it will make it harder to debug. So, the fact that I can see that null
gets passed back tells me that the return is working - but basically function similar to undefined
.
我问这个问题的原因是我听到某些地方听起来像“不要将未定义的变量分配给变量”或其他东西 - 它会使调试变得更难。所以,我可以看到null传回来的事实告诉我返回工作 - 但基本上类似于undefined的功能。
Documentation:
Mozilla Docs Didn't answer my question... google didn't either :\
Mozilla Docs没有回答我的问题...谷歌也没有回答:
This SO Question - was way too broad for what I'm trying to figure out here.
这个SO问题 - 对于我在这里想要解决的问题来说太宽泛了。
9 个解决方案
#1
19
I will argue there is no best way, and even standard functions sometimes choose one or the other.
我认为没有最好的方法,甚至标准功能有时会选择其中一种。
For example:
例如:
-
[[Prototype]]
[[原型]]
Ordinary objects have a [[Prototype]] internal slot, which determines from which other object they inherit from. Of course, there must be a way to say that an object does not inherit from any other one. In this case, "there is no such object" is represented using
null
.普通对象有一个[[Prototype]]内部槽,它决定了它们从哪个对象继承。当然,必须有一种方法可以说对象不会从任何其他对象继承。在这种情况下,使用null表示“没有这样的对象”。
-
Object.getOwnPropertyDescriptor
Object.getOwnPropertyDescriptor
It is expected to return a property descriptor, that is, an object which describes a property (e.g. value, writability, enumerability and configurability). However, the property may not exist. In this case, "there is no such property" is represented using
undefined
.期望返回属性描述符,即描述属性的对象(例如,值,可写性,可枚举性和可配置性)。但是,该财产可能不存在。在这种情况下,使用undefined表示“没有这样的属性”。
-
document.getElementById
的document.getElementById
It is expected to return the element with the given ID. However, there might be no element with that ID. In this case, "there is no such element" is represented using
null
.期望返回具有给定ID的元素。但是,可能没有具有该ID的元素。在这种情况下,使用null表示“没有这样的元素”。
So just choose whatever you prefer or think makes more sense for your specific case.
因此,只需选择您喜欢的任何内容,或者认为对您的具体情况更有意义。
#2
58
Undefined typically refers to something which has not yet been assigned a value (yet). Null refers to something which definitively has no value. In that case, I would recommend returning a null. Note that a function with no specified return value implicitly returns undefined.
未定义通常是指尚未分配值的东西(尚未)。 Null指的是绝对没有价值的东西。在这种情况下,我建议返回null。请注意,没有指定返回值的函数会隐式返回undefined。
From the ECMAScript2015 spec
来自ECMAScript2015规范
4.3.10 undefined value
4.3.10未定义的值
primitive value used when a variable has not been assigned a value
未赋值变量时使用的原始值
4.3.12 null value
4.3.12空值
primitive value that represents the intentional absence of any object value
原始值,表示故意缺少任何对象值
http://www.ecma-international.org/ecma-262/6.0/#sec-terms-and-definitions-undefined-type
http://www.ecma-international.org/ecma-262/6.0/#sec-terms-and-definitions-undefined-type
Further reading:
进一步阅读:
When is null or undefined used in JavaScript?
什么时候在JavaScript中使用null或undefined?
#3
13
I will give you my personal opinionated way of choosing between the two.
我将以两种方式在两者之间进行选择。
My simple question is: does the value, given another input/state/context could be defined to something?
我的简单问题是:给定另一个输入/状态/上下文的值是否可以定义为什么?
If the answer is yes then use null
else use undefined
. More generally any function returning an object should return null
when the intended object does not exist. Because it could exist given another input/state/context.
如果答案是肯定的,则使用null否则使用undefined。更常见的是,当目标对象不存在时,返回对象的任何函数都应返回null。因为它可以存在给定另一个输入/状态/上下文。
null
represents the absence of value for a given input/state/context. It implicitly means that the concept of the value itself exist in the context of your application but may be absent. In your example the concept of a next card exists but the card itself may not exist. null
should be used.
null表示给定输入/状态/上下文缺少值。它隐含地意味着价值的概念本身存在于您的应用程序的上下文中,但可能不存在。在您的示例中,存在下一张卡的概念,但卡本身可能不存在。应该使用null。
undefined
implicitly represents the absence of meaning of that value in your application's context. For example, if I manipulate a user
object with a given set of properties and I try to access the property pikatchu
. The value of this property should be set to undefined
because in my context it doesn't make any sense to have such a property.
undefined隐式表示应用程序上下文中缺少该值的含义。例如,如果我使用给定的属性集操纵用户对象,并尝试访问属性pikatchu。应该将此属性的值设置为undefined,因为在我的上下文中,拥有这样的属性没有任何意义。
#4
4
undefined
is not something you should assign to. You might want to consider to return something else other than undefined
. In your case, even if you don't return anything at all, the result will be undefined
already. So, I'd suggest to go with null
instead.
undefined不是你应该分配的东西。您可能想要考虑返回除undefined之外的其他内容。在您的情况下,即使您根本没有返回任何内容,结果也将是未定义的。所以,我建议改为使用null。
Consider this sample,
考虑这个样本,
function getSomething() {
// .. do something
return undefined;
}
function doSomething() {
// .. I'm not gonna return anything.
}
var a = getSomething();
var b = doSomething();
Above sample result in a === b
, which is undefined
. The difference is that you save 1 statement execution.
上面的样本结果为=== b,未定义。不同之处在于您保存了1个语句执行。
#5
2
Depends on what u need to do with the returned value.
取决于你需要对返回值做什么。
typeof null returns an object. that object has a value of undefined
typeof null返回一个对象。该对象的值为undefined
typeof undefined returns undefined
typeof undefined返回undefined
#6
0
First answer is right. They have theoretically different meaning. However it's not always clear which to pick up.
第一个答案是对的。它们在理论上具有不同的含义。然而,并不总是清楚哪个拿起。
I tend to use null in my development although I think that's completely subjective thing.
我倾向于在我的开发中使用null,尽管我认为这完全是主观的。
I use that mostly because:
我使用它主要是因为:
-
undefined variable might be overwritten in old browsers so returning it is a little bit more complicated. This same issue forces you to use
typeof var === 'undefined'
when getting function results. link未定义的变量可能会在旧浏览器中被覆盖,因此返回它会稍微复杂一些。获取函数结果时,同样的问题迫使您使用typeof var ==='undefined'。链接
-
Other languages tend to use null widely, a lot of them don't even have undefined (php for example). That gives me kind of consistency when quickly swapping between languages.
其他语言往往广泛使用null,其中很多甚至没有undefined(例如php)。这使我在语言之间快速交换时具有一致性。
#7
0
I think it is very debatable what to use. I prefer code that is semantically as accurate as possible, so I think undefined
is appropriate in this case.
我认为使用什么是非常有争议的。我更喜欢在语义上尽可能准确的代码,所以我认为undefined在这种情况下是合适的。
I think of null
assignments as meaning "a variable set to nothing". This is as opposed to undefined
meaning "this thing isn't there at all"
我认为null赋值意味着“变量设置为空”。这与未定义的意思相反“这件事根本不存在”
As a previous answer pointed out, returning undefined
has issues, and it's completely up to you whether that bothers you. It wouldn't bother me.
正如之前的回答所指出的那样,返回undefined会产生问题,这完全取决于你是否会困扰你。它不会打扰我。
#8
0
Here's an example where undefined
makes more sense than null
:
这是一个示例,其中undefined比null更有意义:
I use a wrapper function for JSON.parse
that converts its exception to undefined
:
我使用JSON.parse的包装函数将其异常转换为undefined:
// parses s as JSON if possible and returns undefined otherwise
// return undefined iff s is not a string or not parseable as JSON; undefined is not a valid JSON value https://*.com/a/14946821/524504
function JSON_parse_or_undefined(s) {
if ("string" !== typeof s) return undefined
try {
const p = JSON.parse(s)
return p
} catch (x){}
return undefined
}
Note that null
is valid in JSON while undefined
is not.
请注意,null在JSON中有效,而未定义则不在。
#9
0
I would argue that in this case, null
should be returned.
我认为在这种情况下,应该返回null。
If you consider the question from a theoretical computer science point of view then undefined is used to indicate non-termination/ non-computability (i.e. the placeholder for an undefined point x
of a partial function f
which is often written f(x) = ⊥
).
如果从理论计算机科学的角度考虑问题,则使用undefined来表示非终止/不可计算性(即,部分函数f的未定义点x的占位符,通常写为f(x)=⊥ )。
getNextCard
however seems to be able to compute the next card (if it exists) and also be able to compute if there is no next card. In other words, the function is total since it terminates for every input.
然而,getNextCard似乎能够计算下一张卡(如果它存在)并且还能够计算是否没有下一张卡。换句话说,该函数是完全的,因为它终止于每个输入。
That being said, a special value signalling termination without meaningful result (i.e. "there's no card I can return for this input") is required and this for me is null
not undefined
.
话虽这么说,一个特殊的值信号终止没有有意义的结果(即“我没有卡可以为这个输入返回”)是必需的,这对我来说是空的而不是未定义的。
NOTES:
笔记:
You can see some support for this argument in some other typed languages as well where termination without meaningful result are expressed using an option type (sometimes also referred to as nullable type). An example for this is is Maybe in Haskell.
您可以在其他一些类型语言中看到对此参数的一些支持,其中使用选项类型(有时也称为可空类型)表示没有有意义结果的终止。这方面的一个例子是在Haskell中的Maybe。
On the other hand, we of course do not know what undefined
in JavaScript is really supposed to mean. So, the analogy to undefined is a bit tenous. Moreover, since we always want to work with total functions, this amounts to saying "never return undefined
from a function". Which seems to be a bit strict, since it would limit the use of undefined
to properties/ variables which have not been set.
另一方面,我们当然不知道JavaScript中的undefined是什么意思。因此,对undefined的类比有点过分。此外,由于我们总是希望使用总函数,这相当于说“永远不会从函数返回undefined”。这似乎有点严格,因为它会将undefined的使用限制为尚未设置的属性/变量。
In the end, my personal preference is never to return undefined
where I can return null
and I would also argue that this is the better coding convention (because among other things x !== null
is shorter than typeof x !== 'undefined'
).
最后,我的个人偏好永远不会返回undefined,我可以返回null,我也会认为这是更好的编码约定(因为除其他外x!== null比typeof x更短!=='undefined' )。
#1
19
I will argue there is no best way, and even standard functions sometimes choose one or the other.
我认为没有最好的方法,甚至标准功能有时会选择其中一种。
For example:
例如:
-
[[Prototype]]
[[原型]]
Ordinary objects have a [[Prototype]] internal slot, which determines from which other object they inherit from. Of course, there must be a way to say that an object does not inherit from any other one. In this case, "there is no such object" is represented using
null
.普通对象有一个[[Prototype]]内部槽,它决定了它们从哪个对象继承。当然,必须有一种方法可以说对象不会从任何其他对象继承。在这种情况下,使用null表示“没有这样的对象”。
-
Object.getOwnPropertyDescriptor
Object.getOwnPropertyDescriptor
It is expected to return a property descriptor, that is, an object which describes a property (e.g. value, writability, enumerability and configurability). However, the property may not exist. In this case, "there is no such property" is represented using
undefined
.期望返回属性描述符,即描述属性的对象(例如,值,可写性,可枚举性和可配置性)。但是,该财产可能不存在。在这种情况下,使用undefined表示“没有这样的属性”。
-
document.getElementById
的document.getElementById
It is expected to return the element with the given ID. However, there might be no element with that ID. In this case, "there is no such element" is represented using
null
.期望返回具有给定ID的元素。但是,可能没有具有该ID的元素。在这种情况下,使用null表示“没有这样的元素”。
So just choose whatever you prefer or think makes more sense for your specific case.
因此,只需选择您喜欢的任何内容,或者认为对您的具体情况更有意义。
#2
58
Undefined typically refers to something which has not yet been assigned a value (yet). Null refers to something which definitively has no value. In that case, I would recommend returning a null. Note that a function with no specified return value implicitly returns undefined.
未定义通常是指尚未分配值的东西(尚未)。 Null指的是绝对没有价值的东西。在这种情况下,我建议返回null。请注意,没有指定返回值的函数会隐式返回undefined。
From the ECMAScript2015 spec
来自ECMAScript2015规范
4.3.10 undefined value
4.3.10未定义的值
primitive value used when a variable has not been assigned a value
未赋值变量时使用的原始值
4.3.12 null value
4.3.12空值
primitive value that represents the intentional absence of any object value
原始值,表示故意缺少任何对象值
http://www.ecma-international.org/ecma-262/6.0/#sec-terms-and-definitions-undefined-type
http://www.ecma-international.org/ecma-262/6.0/#sec-terms-and-definitions-undefined-type
Further reading:
进一步阅读:
When is null or undefined used in JavaScript?
什么时候在JavaScript中使用null或undefined?
#3
13
I will give you my personal opinionated way of choosing between the two.
我将以两种方式在两者之间进行选择。
My simple question is: does the value, given another input/state/context could be defined to something?
我的简单问题是:给定另一个输入/状态/上下文的值是否可以定义为什么?
If the answer is yes then use null
else use undefined
. More generally any function returning an object should return null
when the intended object does not exist. Because it could exist given another input/state/context.
如果答案是肯定的,则使用null否则使用undefined。更常见的是,当目标对象不存在时,返回对象的任何函数都应返回null。因为它可以存在给定另一个输入/状态/上下文。
null
represents the absence of value for a given input/state/context. It implicitly means that the concept of the value itself exist in the context of your application but may be absent. In your example the concept of a next card exists but the card itself may not exist. null
should be used.
null表示给定输入/状态/上下文缺少值。它隐含地意味着价值的概念本身存在于您的应用程序的上下文中,但可能不存在。在您的示例中,存在下一张卡的概念,但卡本身可能不存在。应该使用null。
undefined
implicitly represents the absence of meaning of that value in your application's context. For example, if I manipulate a user
object with a given set of properties and I try to access the property pikatchu
. The value of this property should be set to undefined
because in my context it doesn't make any sense to have such a property.
undefined隐式表示应用程序上下文中缺少该值的含义。例如,如果我使用给定的属性集操纵用户对象,并尝试访问属性pikatchu。应该将此属性的值设置为undefined,因为在我的上下文中,拥有这样的属性没有任何意义。
#4
4
undefined
is not something you should assign to. You might want to consider to return something else other than undefined
. In your case, even if you don't return anything at all, the result will be undefined
already. So, I'd suggest to go with null
instead.
undefined不是你应该分配的东西。您可能想要考虑返回除undefined之外的其他内容。在您的情况下,即使您根本没有返回任何内容,结果也将是未定义的。所以,我建议改为使用null。
Consider this sample,
考虑这个样本,
function getSomething() {
// .. do something
return undefined;
}
function doSomething() {
// .. I'm not gonna return anything.
}
var a = getSomething();
var b = doSomething();
Above sample result in a === b
, which is undefined
. The difference is that you save 1 statement execution.
上面的样本结果为=== b,未定义。不同之处在于您保存了1个语句执行。
#5
2
Depends on what u need to do with the returned value.
取决于你需要对返回值做什么。
typeof null returns an object. that object has a value of undefined
typeof null返回一个对象。该对象的值为undefined
typeof undefined returns undefined
typeof undefined返回undefined
#6
0
First answer is right. They have theoretically different meaning. However it's not always clear which to pick up.
第一个答案是对的。它们在理论上具有不同的含义。然而,并不总是清楚哪个拿起。
I tend to use null in my development although I think that's completely subjective thing.
我倾向于在我的开发中使用null,尽管我认为这完全是主观的。
I use that mostly because:
我使用它主要是因为:
-
undefined variable might be overwritten in old browsers so returning it is a little bit more complicated. This same issue forces you to use
typeof var === 'undefined'
when getting function results. link未定义的变量可能会在旧浏览器中被覆盖,因此返回它会稍微复杂一些。获取函数结果时,同样的问题迫使您使用typeof var ==='undefined'。链接
-
Other languages tend to use null widely, a lot of them don't even have undefined (php for example). That gives me kind of consistency when quickly swapping between languages.
其他语言往往广泛使用null,其中很多甚至没有undefined(例如php)。这使我在语言之间快速交换时具有一致性。
#7
0
I think it is very debatable what to use. I prefer code that is semantically as accurate as possible, so I think undefined
is appropriate in this case.
我认为使用什么是非常有争议的。我更喜欢在语义上尽可能准确的代码,所以我认为undefined在这种情况下是合适的。
I think of null
assignments as meaning "a variable set to nothing". This is as opposed to undefined
meaning "this thing isn't there at all"
我认为null赋值意味着“变量设置为空”。这与未定义的意思相反“这件事根本不存在”
As a previous answer pointed out, returning undefined
has issues, and it's completely up to you whether that bothers you. It wouldn't bother me.
正如之前的回答所指出的那样,返回undefined会产生问题,这完全取决于你是否会困扰你。它不会打扰我。
#8
0
Here's an example where undefined
makes more sense than null
:
这是一个示例,其中undefined比null更有意义:
I use a wrapper function for JSON.parse
that converts its exception to undefined
:
我使用JSON.parse的包装函数将其异常转换为undefined:
// parses s as JSON if possible and returns undefined otherwise
// return undefined iff s is not a string or not parseable as JSON; undefined is not a valid JSON value https://*.com/a/14946821/524504
function JSON_parse_or_undefined(s) {
if ("string" !== typeof s) return undefined
try {
const p = JSON.parse(s)
return p
} catch (x){}
return undefined
}
Note that null
is valid in JSON while undefined
is not.
请注意,null在JSON中有效,而未定义则不在。
#9
0
I would argue that in this case, null
should be returned.
我认为在这种情况下,应该返回null。
If you consider the question from a theoretical computer science point of view then undefined is used to indicate non-termination/ non-computability (i.e. the placeholder for an undefined point x
of a partial function f
which is often written f(x) = ⊥
).
如果从理论计算机科学的角度考虑问题,则使用undefined来表示非终止/不可计算性(即,部分函数f的未定义点x的占位符,通常写为f(x)=⊥ )。
getNextCard
however seems to be able to compute the next card (if it exists) and also be able to compute if there is no next card. In other words, the function is total since it terminates for every input.
然而,getNextCard似乎能够计算下一张卡(如果它存在)并且还能够计算是否没有下一张卡。换句话说,该函数是完全的,因为它终止于每个输入。
That being said, a special value signalling termination without meaningful result (i.e. "there's no card I can return for this input") is required and this for me is null
not undefined
.
话虽这么说,一个特殊的值信号终止没有有意义的结果(即“我没有卡可以为这个输入返回”)是必需的,这对我来说是空的而不是未定义的。
NOTES:
笔记:
You can see some support for this argument in some other typed languages as well where termination without meaningful result are expressed using an option type (sometimes also referred to as nullable type). An example for this is is Maybe in Haskell.
您可以在其他一些类型语言中看到对此参数的一些支持,其中使用选项类型(有时也称为可空类型)表示没有有意义结果的终止。这方面的一个例子是在Haskell中的Maybe。
On the other hand, we of course do not know what undefined
in JavaScript is really supposed to mean. So, the analogy to undefined is a bit tenous. Moreover, since we always want to work with total functions, this amounts to saying "never return undefined
from a function". Which seems to be a bit strict, since it would limit the use of undefined
to properties/ variables which have not been set.
另一方面,我们当然不知道JavaScript中的undefined是什么意思。因此,对undefined的类比有点过分。此外,由于我们总是希望使用总函数,这相当于说“永远不会从函数返回undefined”。这似乎有点严格,因为它会将undefined的使用限制为尚未设置的属性/变量。
In the end, my personal preference is never to return undefined
where I can return null
and I would also argue that this is the better coding convention (because among other things x !== null
is shorter than typeof x !== 'undefined'
).
最后,我的个人偏好永远不会返回undefined,我可以返回null,我也会认为这是更好的编码约定(因为除其他外x!== null比typeof x更短!=='undefined' )。