ES5 | When to use null and when to use undefined [duplicate]

时间秒杀一切 提交于 2019-12-11 02:56:13

问题


Possible Duplicate:
Javascript null or undefined

null is a reserved word but not a keyword.
Hence it can not be over-written.

undefined is a built in global that can be over-written. This is why you see jQuery re-define it in its IIFE. Just to make sure it was not over-written.

What it the technical distinction of when to use each as specified in ES 5.

I know that I have seen browsers set an un-created localStorage property to either null or undefined depending upon the browser.

localStorage.not_defined === null // sometimes

localStorage.not_defined === undefined // sometimes

How does ES 5 specify their usage in this case and in general?

ES5 provides not clarification:

8.1 The Undefined Type The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.

8.2 The Null Type The Null type has exactly one value, called null.

http://www.ecma-international.org/publications/standards/Ecma-262.htm


回答1:


The distinction of these two is rather vague and not clarified in the spec.

The common sense is the following: undefined are variables which never have been assigned and non-existing properties.

null however is a state of a variable or property which indicates that it has no value assigned.

Some methods like getElement... explicitely return null to indicate that the resultset is empty. If your function has no return statement, implicitely undefined is returned instead.

In general, always assign null and never undefined.




回答2:


null is a value. The value of nothing is null.

undefined is the lack of a value.

This is how it should be used.

you should never assign undefined to anything. That defeats the purpose. If you want to make your existing property undefined you use the delete keyword.

On the other hand null is a legitimate value to assign to a variable.

jQuery adds an undefined variable to its closure because it is easier to test a === undefined than to write typeof a === 'undefined'.



来源:https://stackoverflow.com/questions/12606306/es5-when-to-use-null-and-when-to-use-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!