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

2019-07-17 03:43发布

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

2条回答
手持菜刀,她持情操
2楼-- · 2019-07-17 03:55

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.

查看更多
对你真心纯属浪费
3楼-- · 2019-07-17 04:02

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'.

查看更多
登录 后发表回答