【转】The && and || Operator in JavaScript
原文: https://blog.mariusschulz.com/2016/05/25/the-andand-and-operator-in-javascript
The && and || Operator in JavaScript
-------------------------------------------------
Similar to other C-like programming languages, JavaScript defines the two operators && and || which represent the logical AND and OR operations, respectively. Using only the two boolean values true and false, we can generate the following truth tables:
// Logical AND operation
true && true; // true
true && false; // false
false && true; // false
false && false; // false
// Logical OR operation
true || true; // true
true || false; // true
false || true; // true
false || false; // false
If applied to boolean values, the && operator only returns true when both of its operands are true (and false in all other cases), while the || operator only returns false when both of its operands are false (and true in all other cases).
Using Logical Operators with Non-Boolean Values
In JavaScript, the logical operators have different semantics than other C-like languages, though. They can operate on expressions of any type, not just booleans. Also, the logical operators do not always return a boolean value, as the specification points out in section 12.12:
The value produced by a
&&or||operator is not necessarily of type Boolean. The value produced will always be the value of one of the two operand expressions.
The following examples showcase some values produced by && and ||:
"foo" && "bar"; // "bar"
"bar" && "foo"; // "foo"
"foo" && ""; // ""
"" && "foo"; // ""
"foo" || "bar"; // "foo"
"bar" || "foo"; // "bar"
"foo" || ""; // "foo"
"" || "foo"; // "foo"
Both && and || result in the value of (exactly) one of their operands:
A && Breturns the value A if A can be coerced intofalse; otherwise, it returns B.A || Breturns the value A if A can be coerced intotrue; otherwise, it returns B.
They select one of their operands, as noted by Kyle Simpson in his You Don't Know JS series:
In fact, I would argue these operators shouldn't even be called "logical operators", as that name is incomplete in describing what they do. If I were to give them a more accurate (if more clumsy) name, I'd call them "selector operators," or more completely, "operand selector operators."
Control Flow Structures and Truthy Values
In practice, you might not even notice that && and || don't always produce a boolean value. The body of control flow structures like if-statements and loops will be executed when the condition evaluates to a "truthy" value, which doesn't have to be a proper boolean:
let values = [1, 2, 3];
while (values.length) {
console.log(values.pop());
}
// 3
// 2
// 1
So when is a value considered "truthy"? In JavaScript, all values are considered "truthy", except for the following six "falsy" values:
falseundefinednullNaN0(both+0and-0)""
The above while-loop works because after popping the last element, values.length returns the "falsy" value 0. Therefore, the loop body won't be executed and the loop terminates.
Truthy and Falsy Return Values
Let's look at an example where it actually matters that && and || don't necessarily produce a boolean value. Imagine you're developing a web application. Users can be signed out, in which case the user object is null, or they can be signed in, in which case the user object exists and has an isAdmin property.
If you wanted to check whether the current user is an administrator, you would first check whether the user is authenticated (that is, user is not null). Then, you would access the isAdmin property and check whether it's "truthy":
let user = { isAdmin: true };
// ...
if (user && user.isAdmin) {
// ...
}
You might even consider extracting the expression user && user.isAdmin into a separate isAdministrator function so you can use it in multiple places without repeating yourself:
function isAdministrator(user) {
return user && user.isAdmin;
}
let user = { isAdmin: true };
if (isAdministrator(user)) {
// ...
}
For user objects with a boolean isAdmin property, either true or false will be returned, just as intended:
isAdministrator({ isAdmin: true }); // true
isAdministrator({ isAdmin: false }); // false
But what happens if the user object is null?
isAdministrator(null); // null
The expression user && user.isAdmin evaluates to null, its first operand, because usercontains a "falsy" value. Now, a function called isAdministrator should only return boolean values, as the prefix is in the name suggests.
Coercion to Boolean Values
In JavaScript, a common way to coerce any value into a boolean is to apply the logical NOT operator ! twice:
function isAdministrator(user) {
return !!(user && user.isAdmin);
}
The ! operator, produces the value false if its single operand can be coerced into true; otherwise, it returns true. The result is always a proper boolean, but the truthiness of the operand is flipped. Applying the ! operator twice undoes the flipping:
!!true = !false = true
!!false = !true = false
!!0 = !true = false
!!1 = !false = true
Another option would've been to call the Boolean function, which is a slightly more explicit way to convert a given value to a proper boolean value:
function isAdministrator(user) {
return Boolean(user && user.isAdmin);
}
Conclusion
In JavaScript, && and || don't always produce a boolean value. Both operators always return the value of one of their operand expressions. Using the double negation !! or the Booleanfunction, "truthy" and "falsy" values can be converted to proper booleans.
【转】The && and || Operator in JavaScript的更多相关文章
- What is the !! (not not) operator in JavaScript?
What is the !! (not not) operator in JavaScript? 解答1 Coerces强制 oObject to boolean. If it was falsey ...
- The tilde ( ~ ) operator in JavaScript
From the JavaScript Reference on MDC, ~ (Bitwise NOT) Performs the NOT operator on each bit. NOT a y ...
- [TypeScript] Use the JavaScript “in” operator for automatic type inference in TypeScript
Sometimes we might want to make a function more generic by having it accept a union of different typ ...
- JavaScript简易教程(转)
原文:http://www.cnblogs.com/yanhaijing/p/3685304.html 这是我所知道的最完整最简洁的JavaScript基础教程. 这篇文章带你尽快走进JavaScri ...
- JavaScript constructors, prototypes, and the `new` keyword
Are you baffled(阻碍:使迷惑) by the new operator in JavaScript? Wonder what the difference between a func ...
- JavaScript简易教程
这是我所知道的最完整最简洁的JavaScript基础教程. 这篇文章带你尽快走进JavaScript的世界——前提是你有一些编程经验的话.本文试图描述这门语言的最小子集.我给这个子集起名叫做“Java ...
- 【转】Expressions versus statements in JavaScript
原文地址:http://www.2ality.com/2012/09/expressions-vs-statements.html Update 2012-09-21: New in Sect. 4: ...
- javascript prototype原型链的原理
javascript prototype原型链的原理 说到prototype,就不得不先说下new的过程. 我们先看看这样一段代码: <script type="text/javasc ...
- JavaScript技巧手冊
js小技巧 每一项都是js中的小技巧,但十分的有用! 1.document.write(""); 输出语句 2.JS中的凝视为// 3.传统的HTML文档顺序是:documen ...
随机推荐
- 【转载】“惊群”,看看nginx是怎么解决它的
原文:http://blog.csdn.net/russell_tao/article/details/7204260 在说nginx前,先来看看什么是“惊群”?简单说来,多线程/多进程(linux下 ...
- Python基础系列----语法、数据类型、变量、编码
1.基本语法 Python ...
- MySQL的数据引擎讲解
一.MySQL的数据引擎讲解 在MySQL数据库中,常用的引擎主要就是2个:Innodb和MyIASM. 1.简单介绍这两种引擎,以及该如何去选择. a.Innodb引擎,Innodb引擎提供了对数据 ...
- LOJ #6280. 数列分块入门 4-分块(区间加法、区间求和)
#6280. 数列分块入门 4 内存限制:256 MiB时间限制:500 ms标准输入输出 题目类型:传统评测方式:文本比较 上传者: hzwer 提交提交记录统计测试数据讨论 题目描述 给出一个 ...
- CodeForces 779E Bitwise Formula
位运算,枚举. 按按分开计算,枚举$?$是$0$还是$1$,分别计算出$sum$,然后就可以知道该位需要填$1$还是$0$了. #include<map> #include<set& ...
- 每日一刷(2018多校水题+2016icpc水题)
11.9 线段树 http://acm.hdu.edu.cn/showproblem.php?pid=6315 求逆序对个数 http://acm.hdu.edu.cn/showproblem.php ...
- HTTP Slow Attack测试工具SlowHTTPTest
HTTP Slow Attack测试工具SlowHTTPTest Slow Attack是HTTP常见的一种拒绝服务攻击方式.它通过消耗服务器的系统资源和连接数,导致Web服务器无法正常工作.常见 ...
- python strip() 函数和 split() 函数的详解及实例
strip是删除的意思:split则是分割的意思.strip可以删除字符串的某些字符,split则是根据规定的字符将字符串进行分割. 1.Python strip()函数 介绍 函数原型 声明:s为字 ...
- 【二分】Defense Lines
[UVa1471] Defense Lines 算法入门经典第8章8-8 (P242) 题目大意:将一个序列删去一个连续子序列,问最长的严格上升子序列 (N<=200000) 试题分析:算法1: ...
- BZOJ 3083 遥远的国度(树链剖分+线段树)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3083 [题目大意] 链修改,子树最小值查询和换根操作 [题解] 树链剖分练习题. [代 ...