null === undefined_【英】两个“非值”:undefined 和 null

前言

本期英文由@Dr. Axel Rauschmayer分享。

英文从这开始~~

Most programming languages have only one value for “no value” or “empty reference”. For example, that value is null in Java. JavaScript has two of those special values: undefined and null. They are basically the same (something that will change with ECMAScript 6, as will be explained in the last post of this series), but they are used slightly differently.

undefined is assigned via the language itself. Variables that have not been initialized yet have this value:

> var foo;

> foo

undefined

Similarly, JavaScript assigns undefined to missing parameters:

> function id(x) { return x }

> id()

undefined

null is used by programmers to explicitly indicate that a value is missing. E.g. for JSON.stringify():

> console.log(JSON.stringify({ first: 'Jane' }, null, 4))

{

"first": "Jane"

}

Check: does a variable have a value?

If you want to know whether a variable v has a value, you normally have to check for both undefined and null. Fortunately, both values are truthy. Thus, checking for truthiness via if performs both checks at the same time:

if (v) {

// v has a value

} else {

// v does not have a value

}

You’ll see more examples of the above check in the post for quirk 5 about parameter handling. There is one caveat: this check also interprets false, -0, +0, NaN and '' as “no value”. If that isn’t what you want then you can’t use it. You have two choices.

Some people advocate lenient non-equality (!=) to check that v is neither undefined nor null:

if (v != null) {

// v has a value

} else {

// v does not have a value

}

However, that requires you to know that != considers null to be only equal to itself and to undefined. I prefer the more descriptive use of !==:

if (v !== undefined && v !== null) {

// v has a value

} else {

// v does not have a value

}

Performance-wise, all three checks shown in this section are more or less the same. Hence, which one you will end up using depends on your needs and your taste. Some minification tools even rewrite the last check to a check via !=. 

关于本文 作者:@Dr. Axel Rauschmayer 原文:https://2ality.com/2013/04/quirk-undefined.html

74e844288a9f8ff65cf906d5b747d570.png

为你推荐

【第1244期】详解Object.create(null)

【英】在JavaScript中使用查询参数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值