I've been writing JavaScript for quite a long time now, and I have never had a reason to use null
. It seems that undefined
is always preferable and serves the same purpose programmatically. What are some practical reasons to use null
instead of undefined
?
我已经编写JavaScript很长时间了,我从来没有理由使用null。似乎未定义总是可取的,并且以编程方式提供相同的目的。使用空值而不是未定义的实际原因是什么?
11 个解决方案
#1
32
Null and undefined are essentially two different values that mean the same thing. The only difference is in the conventions of how you use them in your system. As some have mentioned, some people use null for meaning "no object" where you might sometimes get an object while undefined means that no object was expected (or that there was an error). My problem with that is its completely arbitrary, and totally unnecessary.
Null和undefined本质上是两个不同的值,意思相同。唯一的区别是你如何在你的系统中使用它们。正如有些人所提到的,有些人使用null表示“没有对象”,有时你可能会得到一个对象,而没有定义意味着没有对象被期望(或者有一个错误)。我的问题是它完全是任意的,完全没有必要。
That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are always undefined.
也就是说,有一个主要的区别——没有初始化的变量(包括没有参数传递的函数参数,还有其他的)总是没有定义的。
Which is why in my code I never use null unless something I don't control returns null (regex matching for example). The beauty of this is it simiplifies things a lot. I never have to check if x === undefined || x === null. And if you're in the habit of using == or simply stuff like if(x) ... . Stop it. !x
will evaluate to true for an empty string, 0, null, NaN - ie things you probably don't want. If you want to write javascript that isn't awful, always use triple equals === and never use null (use undefined instead). It'll make your life way easier.
这就是为什么在我的代码中我从不使用null,除非我不控制返回null(例如正则表达式匹配)。它的美妙之处在于它能将事情进行很多的类比。我不需要检查x是否=== undefined || x === = null。如果你习惯用==或者简单地用if(x)……阻止它。!对于空字符串,x的值为true, 0, null, NaN - ie,这些都是你可能不想要的。如果你想写一个不太糟糕的javascript,一定要使用triple equals === =,永远不要使用null(使用undefined代替)。这会让你的生活更轻松。
#2
59
I don't really have an answer, but according to Nicholas C. Zakas, page 30 of his book "Professional JavaScript for Web Developers":
我没有确切的答案,但根据Nicholas C. Zakas的书《Web开发人员的专业JavaScript》的第30页,他说:
When defining a variable that is meant to later hold an object, it is advisable to initialize the variable to
null
as opposed to anything else. That way, you can explicitly check for the valuenull
to determine if the variable has been filled with an object reference at a later time当定义用于稍后保存对象的变量时,建议将变量初始化为null,而不是其他任何东西。通过这种方式,您可以显式地检查值null,以确定该变量是否在稍后填充了对象引用
#3
10
You might adopt the convention suggested here, but there really is no good reason to. It is not used consistently enough to be meaningful.
你可以通过这里建议的公约,但确实没有充分的理由。它的使用并不总是有意义的。
In order to make the convention useful, you first must know that the called function follows the convention. Then you have to explicitly test the returned value and decide what to do. If you get undefined, you can assume that some kind of error occurred that the called function knew about. But if an error happened, and the function knew about it, and it is useful to send that out into the wider environment, why not use an error object? i.e. throw an error?
为了使约定有用,您首先必须知道被调用的函数遵循约定。然后,您必须显式地测试返回的值,并决定要做什么。如果没有定义,可以假设调用函数知道发生了某种错误。但是,如果发生了错误,并且函数知道错误,那么将错误发送到更广泛的环境中是有用的,为什么不使用错误对象呢?即抛出一个错误?
So at the end of the day, the convention is practically useless in anything other than very small programs in simple environments.
所以最后,除了在简单的环境中使用很小的程序外,约定在任何地方都是无用的。
#4
9
undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it has no value.
无定义是指事物不存在的概念;它没有类型,而且在这个范围内之前从未被引用过;null是已知存在的值,但它没有值。
#5
6
Everyone has their own way of coding and their own internal semantics, but over the years I have found this to be the most intuitive advice that I give people who ask this question: when in doubt, do what JavaScript does.
每个人都有自己的编码方式和自己的内部语义,但多年来,我发现这是我给那些问这个问题的人的最直观的建议:当有疑问时,做JavaScript做的事。
Let's say you are working with object properties like options for a jQuery plugin...ask yourself what value JavaScript gives a property that has yet to be defined -- the answer is undefined
. So in this context, I would initialize these types of things with 'undefined' to be consistent with JavaScript (for variables, you can do var myVar;
instead of var myVar = undefined;
).
假设您正在处理对象属性,比如jQuery插件的选项……问问自己,JavaScript为一个尚未定义的属性提供了什么值——答案是没有定义的。在这种情况下,我将用'undefined'初始化这些类型的东西以与JavaScript保持一致(对于变量,可以做var myVar;而不是var myVar = undefined;)
Now let's say you are doing DOM manipulation...what value does JavaScript assign to non-existent elements? The answer is null
. This is the value I would initialize with if you are creating a placeholder variable that will later hold a reference to an element, document fragment, or similar that relates to the DOM.
现在假设你在做DOM操作…JavaScript为不存在的元素赋值什么值?答案是零。如果您正在创建一个占位符变量,稍后该变量将保存对与DOM相关的元素、文档片段或类似元素的引用,那么我将使用这个值进行初始化。
If you're working with JSON, then a special case needs to be made: for undefined property values, you should either set them to ""
or null
because a value of undefined
is not considered proper JSON format.
如果您使用的是JSON,那么需要做一个特殊的情况:对于未定义的属性值,您应该将它们设置为“”或null,因为未定义的值不被认为是合适的JSON格式。
With this said, as a previous poster has expressed, if you find that you're initializing stuff with null
or undefined
more than once in a blue moon, then maybe you should reconsider how you go about coding your app.
有了这个,正如前面的海报所表达的,如果你发现你正在用null或undefined进行多次初始化,那么也许你应该重新考虑如何编写你的应用程序。
#6
2
DOM nodes and elements are not undefined, but may be null.
DOM节点和元素不是未定义的,但可能是空的。
-
The nextSibling of the last child of an element is null.
元素最后一个子元素的nextSibling是null。
-
The previousSibling of the first child is null.
第一个孩子的前科是无效的。
-
A document.getElementById reference is null if the element does not exist in the document.
一个文档。如果文档中不存在元素,则getElementById引用为null。
But in none of these cases is the value undefined; there just is no node there.
但在这些情况中,没有一个价值是没有定义的;这里没有节点。
#7
1
I completely disagree that usage null or undefined is unnecessary. undefined is thing which keeping alive whole prototype chaining process. So compiler only with null can't check if this property just equal to null, or its not defined in endpoint prototype. In other dynamic typed languages(f.e. Python) it throws exception if you want access to not defined property, but for prototype-based languages compiler should also check parent prototypes and here are the place when undefined need most.
我完全不同意使用null或undefined是不必要的。未定义是保持整个原型链接过程的活动。所以只有null的编译器不能检查这个属性是否等于null,或者它没有在端点原型中定义。在其他动态类型语言中(f.e。如果您想访问未定义的属性,它会抛出异常,但是对于基于原型的语言,编译器也应该检查父原型,这里是未定义的最需要的地方。
Whole meaning of using null is just bind variable or property with object which is singleton and have meaning of emptiness,and also null usage have performance purposes. This 2 code have difference execution time.
使用null的全部含义是将变量或属性绑定到对象上,对象是单元素的,具有空性的含义,并且null用法也具有性能目的。这两个代码有不同的执行时间。
var p1 = function(){this.value = 1};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
p = new p1();
if(index > 50000000){
p.x = "some_string";
}
return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)
var p2 = function(){this.value = 1, p.x = null};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
p = new p2();
if(index > 50000000){
p.x = "some_string";
}
return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)
#8
1
A useful property in null that undefined does not qualifies:
空中一个有用的、未定义的属性不限定:
> null + 3
3
> undefined + 3
NaN
I use null
when I want to 'turn off' a numeric value, or to initialize some. My last use was manipulating css transform:
当我想要“关闭”一个数值或初始化一些数值时,我使用null。我最后一次使用css转换:
const transforms = { perspective : null, rotateX : null };
// if already set, increase, if not, set to x
runTimeFunction((x) => { trasforms.perspective += x; });
// still useful, as setting perspective to 0 is different than turning it off
runTimeFunction2((x) => { transforms.perspective = null; });
// toCss will check for 'null' values and not set then at all
runTimeFunction3(() => { el.style.transform = toCss(transforms); });
Not sure if I should use this property thought...
不确定我是否应该使用这个属性思想……
#9
0
I'm working through this exact question right now, and looking at the following philosophy:
我现在正在研究这个问题,并观察下面的哲学:
- Any function that is intended to return a result should return null if it fails to find a result
- 任何要返回结果的函数都应该返回null,如果它没有找到结果
- Any function that is NOT intended to return a result implicitly returns undefined.
- 任何不打算返回结果的函数都会隐式返回未定义的结果。
For me, this question is significant because anyone calling a function that returns a result should have no question as to whether to test for undefined vs null.
对我来说,这个问题很重要,因为任何调用返回结果的函数的人都不应该怀疑是否要测试未定义vs null。
This answer does not attempt to address:
此答案不试图说明:
- Property values of null vs undefined
- 空值与未定义的属性值
- Variables within your functions being null vs undefined
- 函数中的变量是空的vs是未定义的
In my opinion, variables are your own business and not a part of your API, and properties in any OO system are defined and therefore should be defined with value different from what they would be if not defined (null for defined, undefined is what you get when accessing something that is not in your object).
在我看来,变量是你自己的事,而不是API的一部分,和属性定义在任何面向对象系统中,因此应该与价值定义不同于他们如果没有定义(零的定义,定义是什么你会得到当访问的东西不是在你的对象)。
#10
0
Here's a reason: var undefined = 1
is legal javascript, but var null = 1
is a syntax error. The difference is that null
is a language keyword, while undefined
is, for some reason, not.
原因是:var undefined = 1是合法的javascript,但var null = 1是一个语法错误。不同之处在于null是一个语言关键字,而undefined则不是。
If your code relies on comparisons to undefined
as if it's a keyword (if (foo == undefined)
-- a very easy mistake to make) that only works because nobody has defined a variable with that name. All that code is vulnerable to someone accidentally or maliciously defining a global variable with that name. Of course, we all know that accidentally defining a global variable is totally impossible in javascript...
如果您的代码依赖于与undefined的比较,就好像它是一个关键字(If (foo = undefined)——这是一个很容易犯的错误),那么它只会工作,因为没有人用那个名称定义过变量。所有这些代码都容易受到意外或恶意地定义具有该名称的全局变量的影响。当然,我们都知道在javascript中不小心定义全局变量是完全不可能的…
#11
0
At the end of the day, because both null
and undefined
coerce to the same value (Boolean(undefined) === false && Boolean(null) === false
), you can technically use either to get the job done. However, there is right way, IMO.
-
Leave the usage of
undefined
to the JavaScript compiler.将未定义的用法留给JavaScript编译器。
undefined
is used to describe variables that do not point to a reference. It is something that the JS compiler will take care for you. At compile time the JS engine will set the value of all hoisted variables toundefined
. As the engine steps through the code and values becomes available the engine will assign respective values to respective variables. For those variables for whom it did not find values, the variables would continue to maintain a reference to the primitiveundefined
.未定义用于描述不指向引用的变量。这是JS编译器会关心的问题。在编译时,JS引擎将所有提升变量的值设置为未定义。当引擎通过代码和值执行步骤时,引擎将为各自的变量分配相应的值。对于那些没有找到值的变量,变量将继续维护对未定义原语的引用。
-
Only use null if you explicitly want to denote the value of a variable as having "no value".
只有在显式地表示变量的值为“无值”时才使用null。
As @com2gz states:
null
is used to define something programmatically empty.undefined
is meant to say that the reference is not existing. Anull
value has a defined reference to "nothing". If you are calling a non-existing property of an object, then you will getundefined
. If I would make that property intentionally empty, then it must benull
so you know that it's on purpose.@com2gz状态:null用于以编程的方式定义一些空的东西。undefined表示引用不存在。空值具有“无”的定义引用。如果您正在调用一个对象的非存在属性,那么您将得到未定义的。如果我故意让这个属性为空,那么它必须为空,这样你就知道它是故意的。
TLDR; Don't use the undefined
primitive. It's a value that the JS compiler will automatically set for you when you declare variables without assignment or if you try to access properties of objects for which there is no reference. On the other hand, use null
if and only if you intentionally want a variable to have "no value".
TLDR;不要使用未定义的原语。当您在没有赋值的情况下声明变量或试图访问没有引用的对象的属性时,JS编译器会自动为您设置这个值。另一方面,如果您有意要一个变量具有“无值”,则使用null。
I never explicitly set anything to undefined (and I haven't come across this in the many codebases I've interacted with). Also, I rarely use null
. The only times I use null
is when I want to denote the value of an argument to a function as having no value, i.e.,:
我从来没有显式地将任何内容设置为undefined(在与之交互的许多代码基中,我没有遇到过这种情况)。而且,我很少使用null。我使用null的唯一情况是,当我想将参数的值表示为没有值的函数时,即:
function printArguments(a,b) {
console.log(a,b);
}
printArguments(null, " hello") // logs: null hello
#1
32
Null and undefined are essentially two different values that mean the same thing. The only difference is in the conventions of how you use them in your system. As some have mentioned, some people use null for meaning "no object" where you might sometimes get an object while undefined means that no object was expected (or that there was an error). My problem with that is its completely arbitrary, and totally unnecessary.
Null和undefined本质上是两个不同的值,意思相同。唯一的区别是你如何在你的系统中使用它们。正如有些人所提到的,有些人使用null表示“没有对象”,有时你可能会得到一个对象,而没有定义意味着没有对象被期望(或者有一个错误)。我的问题是它完全是任意的,完全没有必要。
That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are always undefined.
也就是说,有一个主要的区别——没有初始化的变量(包括没有参数传递的函数参数,还有其他的)总是没有定义的。
Which is why in my code I never use null unless something I don't control returns null (regex matching for example). The beauty of this is it simiplifies things a lot. I never have to check if x === undefined || x === null. And if you're in the habit of using == or simply stuff like if(x) ... . Stop it. !x
will evaluate to true for an empty string, 0, null, NaN - ie things you probably don't want. If you want to write javascript that isn't awful, always use triple equals === and never use null (use undefined instead). It'll make your life way easier.
这就是为什么在我的代码中我从不使用null,除非我不控制返回null(例如正则表达式匹配)。它的美妙之处在于它能将事情进行很多的类比。我不需要检查x是否=== undefined || x === = null。如果你习惯用==或者简单地用if(x)……阻止它。!对于空字符串,x的值为true, 0, null, NaN - ie,这些都是你可能不想要的。如果你想写一个不太糟糕的javascript,一定要使用triple equals === =,永远不要使用null(使用undefined代替)。这会让你的生活更轻松。
#2
59
I don't really have an answer, but according to Nicholas C. Zakas, page 30 of his book "Professional JavaScript for Web Developers":
我没有确切的答案,但根据Nicholas C. Zakas的书《Web开发人员的专业JavaScript》的第30页,他说:
When defining a variable that is meant to later hold an object, it is advisable to initialize the variable to
null
as opposed to anything else. That way, you can explicitly check for the valuenull
to determine if the variable has been filled with an object reference at a later time当定义用于稍后保存对象的变量时,建议将变量初始化为null,而不是其他任何东西。通过这种方式,您可以显式地检查值null,以确定该变量是否在稍后填充了对象引用
#3
10
You might adopt the convention suggested here, but there really is no good reason to. It is not used consistently enough to be meaningful.
你可以通过这里建议的公约,但确实没有充分的理由。它的使用并不总是有意义的。
In order to make the convention useful, you first must know that the called function follows the convention. Then you have to explicitly test the returned value and decide what to do. If you get undefined, you can assume that some kind of error occurred that the called function knew about. But if an error happened, and the function knew about it, and it is useful to send that out into the wider environment, why not use an error object? i.e. throw an error?
为了使约定有用,您首先必须知道被调用的函数遵循约定。然后,您必须显式地测试返回的值,并决定要做什么。如果没有定义,可以假设调用函数知道发生了某种错误。但是,如果发生了错误,并且函数知道错误,那么将错误发送到更广泛的环境中是有用的,为什么不使用错误对象呢?即抛出一个错误?
So at the end of the day, the convention is practically useless in anything other than very small programs in simple environments.
所以最后,除了在简单的环境中使用很小的程序外,约定在任何地方都是无用的。
#4
9
undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it has no value.
无定义是指事物不存在的概念;它没有类型,而且在这个范围内之前从未被引用过;null是已知存在的值,但它没有值。
#5
6
Everyone has their own way of coding and their own internal semantics, but over the years I have found this to be the most intuitive advice that I give people who ask this question: when in doubt, do what JavaScript does.
每个人都有自己的编码方式和自己的内部语义,但多年来,我发现这是我给那些问这个问题的人的最直观的建议:当有疑问时,做JavaScript做的事。
Let's say you are working with object properties like options for a jQuery plugin...ask yourself what value JavaScript gives a property that has yet to be defined -- the answer is undefined
. So in this context, I would initialize these types of things with 'undefined' to be consistent with JavaScript (for variables, you can do var myVar;
instead of var myVar = undefined;
).
假设您正在处理对象属性,比如jQuery插件的选项……问问自己,JavaScript为一个尚未定义的属性提供了什么值——答案是没有定义的。在这种情况下,我将用'undefined'初始化这些类型的东西以与JavaScript保持一致(对于变量,可以做var myVar;而不是var myVar = undefined;)
Now let's say you are doing DOM manipulation...what value does JavaScript assign to non-existent elements? The answer is null
. This is the value I would initialize with if you are creating a placeholder variable that will later hold a reference to an element, document fragment, or similar that relates to the DOM.
现在假设你在做DOM操作…JavaScript为不存在的元素赋值什么值?答案是零。如果您正在创建一个占位符变量,稍后该变量将保存对与DOM相关的元素、文档片段或类似元素的引用,那么我将使用这个值进行初始化。
If you're working with JSON, then a special case needs to be made: for undefined property values, you should either set them to ""
or null
because a value of undefined
is not considered proper JSON format.
如果您使用的是JSON,那么需要做一个特殊的情况:对于未定义的属性值,您应该将它们设置为“”或null,因为未定义的值不被认为是合适的JSON格式。
With this said, as a previous poster has expressed, if you find that you're initializing stuff with null
or undefined
more than once in a blue moon, then maybe you should reconsider how you go about coding your app.
有了这个,正如前面的海报所表达的,如果你发现你正在用null或undefined进行多次初始化,那么也许你应该重新考虑如何编写你的应用程序。
#6
2
DOM nodes and elements are not undefined, but may be null.
DOM节点和元素不是未定义的,但可能是空的。
-
The nextSibling of the last child of an element is null.
元素最后一个子元素的nextSibling是null。
-
The previousSibling of the first child is null.
第一个孩子的前科是无效的。
-
A document.getElementById reference is null if the element does not exist in the document.
一个文档。如果文档中不存在元素,则getElementById引用为null。
But in none of these cases is the value undefined; there just is no node there.
但在这些情况中,没有一个价值是没有定义的;这里没有节点。
#7
1
I completely disagree that usage null or undefined is unnecessary. undefined is thing which keeping alive whole prototype chaining process. So compiler only with null can't check if this property just equal to null, or its not defined in endpoint prototype. In other dynamic typed languages(f.e. Python) it throws exception if you want access to not defined property, but for prototype-based languages compiler should also check parent prototypes and here are the place when undefined need most.
我完全不同意使用null或undefined是不必要的。未定义是保持整个原型链接过程的活动。所以只有null的编译器不能检查这个属性是否等于null,或者它没有在端点原型中定义。在其他动态类型语言中(f.e。如果您想访问未定义的属性,它会抛出异常,但是对于基于原型的语言,编译器也应该检查父原型,这里是未定义的最需要的地方。
Whole meaning of using null is just bind variable or property with object which is singleton and have meaning of emptiness,and also null usage have performance purposes. This 2 code have difference execution time.
使用null的全部含义是将变量或属性绑定到对象上,对象是单元素的,具有空性的含义,并且null用法也具有性能目的。这两个代码有不同的执行时间。
var p1 = function(){this.value = 1};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
p = new p1();
if(index > 50000000){
p.x = "some_string";
}
return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)
var p2 = function(){this.value = 1, p.x = null};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
p = new p2();
if(index > 50000000){
p.x = "some_string";
}
return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)
#8
1
A useful property in null that undefined does not qualifies:
空中一个有用的、未定义的属性不限定:
> null + 3
3
> undefined + 3
NaN
I use null
when I want to 'turn off' a numeric value, or to initialize some. My last use was manipulating css transform:
当我想要“关闭”一个数值或初始化一些数值时,我使用null。我最后一次使用css转换:
const transforms = { perspective : null, rotateX : null };
// if already set, increase, if not, set to x
runTimeFunction((x) => { trasforms.perspective += x; });
// still useful, as setting perspective to 0 is different than turning it off
runTimeFunction2((x) => { transforms.perspective = null; });
// toCss will check for 'null' values and not set then at all
runTimeFunction3(() => { el.style.transform = toCss(transforms); });
Not sure if I should use this property thought...
不确定我是否应该使用这个属性思想……
#9
0
I'm working through this exact question right now, and looking at the following philosophy:
我现在正在研究这个问题,并观察下面的哲学:
- Any function that is intended to return a result should return null if it fails to find a result
- 任何要返回结果的函数都应该返回null,如果它没有找到结果
- Any function that is NOT intended to return a result implicitly returns undefined.
- 任何不打算返回结果的函数都会隐式返回未定义的结果。
For me, this question is significant because anyone calling a function that returns a result should have no question as to whether to test for undefined vs null.
对我来说,这个问题很重要,因为任何调用返回结果的函数的人都不应该怀疑是否要测试未定义vs null。
This answer does not attempt to address:
此答案不试图说明:
- Property values of null vs undefined
- 空值与未定义的属性值
- Variables within your functions being null vs undefined
- 函数中的变量是空的vs是未定义的
In my opinion, variables are your own business and not a part of your API, and properties in any OO system are defined and therefore should be defined with value different from what they would be if not defined (null for defined, undefined is what you get when accessing something that is not in your object).
在我看来,变量是你自己的事,而不是API的一部分,和属性定义在任何面向对象系统中,因此应该与价值定义不同于他们如果没有定义(零的定义,定义是什么你会得到当访问的东西不是在你的对象)。
#10
0
Here's a reason: var undefined = 1
is legal javascript, but var null = 1
is a syntax error. The difference is that null
is a language keyword, while undefined
is, for some reason, not.
原因是:var undefined = 1是合法的javascript,但var null = 1是一个语法错误。不同之处在于null是一个语言关键字,而undefined则不是。
If your code relies on comparisons to undefined
as if it's a keyword (if (foo == undefined)
-- a very easy mistake to make) that only works because nobody has defined a variable with that name. All that code is vulnerable to someone accidentally or maliciously defining a global variable with that name. Of course, we all know that accidentally defining a global variable is totally impossible in javascript...
如果您的代码依赖于与undefined的比较,就好像它是一个关键字(If (foo = undefined)——这是一个很容易犯的错误),那么它只会工作,因为没有人用那个名称定义过变量。所有这些代码都容易受到意外或恶意地定义具有该名称的全局变量的影响。当然,我们都知道在javascript中不小心定义全局变量是完全不可能的…
#11
0
At the end of the day, because both null
and undefined
coerce to the same value (Boolean(undefined) === false && Boolean(null) === false
), you can technically use either to get the job done. However, there is right way, IMO.
-
Leave the usage of
undefined
to the JavaScript compiler.将未定义的用法留给JavaScript编译器。
undefined
is used to describe variables that do not point to a reference. It is something that the JS compiler will take care for you. At compile time the JS engine will set the value of all hoisted variables toundefined
. As the engine steps through the code and values becomes available the engine will assign respective values to respective variables. For those variables for whom it did not find values, the variables would continue to maintain a reference to the primitiveundefined
.未定义用于描述不指向引用的变量。这是JS编译器会关心的问题。在编译时,JS引擎将所有提升变量的值设置为未定义。当引擎通过代码和值执行步骤时,引擎将为各自的变量分配相应的值。对于那些没有找到值的变量,变量将继续维护对未定义原语的引用。
-
Only use null if you explicitly want to denote the value of a variable as having "no value".
只有在显式地表示变量的值为“无值”时才使用null。
As @com2gz states:
null
is used to define something programmatically empty.undefined
is meant to say that the reference is not existing. Anull
value has a defined reference to "nothing". If you are calling a non-existing property of an object, then you will getundefined
. If I would make that property intentionally empty, then it must benull
so you know that it's on purpose.@com2gz状态:null用于以编程的方式定义一些空的东西。undefined表示引用不存在。空值具有“无”的定义引用。如果您正在调用一个对象的非存在属性,那么您将得到未定义的。如果我故意让这个属性为空,那么它必须为空,这样你就知道它是故意的。
TLDR; Don't use the undefined
primitive. It's a value that the JS compiler will automatically set for you when you declare variables without assignment or if you try to access properties of objects for which there is no reference. On the other hand, use null
if and only if you intentionally want a variable to have "no value".
TLDR;不要使用未定义的原语。当您在没有赋值的情况下声明变量或试图访问没有引用的对象的属性时,JS编译器会自动为您设置这个值。另一方面,如果您有意要一个变量具有“无值”,则使用null。
I never explicitly set anything to undefined (and I haven't come across this in the many codebases I've interacted with). Also, I rarely use null
. The only times I use null
is when I want to denote the value of an argument to a function as having no value, i.e.,:
我从来没有显式地将任何内容设置为undefined(在与之交互的许多代码基中,我没有遇到过这种情况)。而且,我很少使用null。我使用null的唯一情况是,当我想将参数的值表示为没有值的函数时,即:
function printArguments(a,b) {
console.log(a,b);
}
printArguments(null, " hello") // logs: null hello