
正文
【转】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 ...
随机推荐- 查看LINUX进程内存占用情况
可以直接使用top命令后,查看%MEM的内容.可以选择按进程查看或者按用户查看,如想查看oracle用户的进程内存使用情况的话可以使用如下的命令: (1)top top命令是Linux下常用的性能分析 ...
- guacamole 0.9.9安装与配置
以下命令很多都需要管理权限,建议使用管理员账号执行,遇到问题可以留言. 1.首先需要安装guacamole所需要的依赖库 必需安装的库有:Cairo.libjpeg-turbo.libpng.OSSP ...
- codeforces 333B - Chips
注意:横向纵向交叉时,只要两条边不是正中的边(当n&1!=1),就可以余下两个chip. 代码里数组a[][]第二维下标 0表示横向边,1表示纵向边. #include<stdio.h& ...
- HDU 4135 Co-prime
思路:直接用求(b,1)范围内互质的数,(a-1,1)范围内互质的数.再求反 就是敲一下容斥模板 #include<cstdio> #include<cstring> #inc ...
- SLC和MLC闪存芯片的区别
许多人对闪存的SLC和MLC区分不清.就拿目前热销的MP3随身听来说,是买SLC还是MLC闪存芯片的呢?在这里先告诉大家,如果你对容量要求不高,但是对机器质量.数据的安全性.机器寿命等方面要求较高,那 ...
- 转:如何让LoadRunner实现多个场景运行?
场景分析: 有3个不同的场景,分别为搜索,下载,上传,其中3个场景执行顺序为按照搜索->下载->上传流程操作:哪么如何让Loadrunner中如何实现多个场景运行: 方法1:利用Loadr ...
- 【Alpha】第一次项目冲刺
今日站立式会议照片 每个人的工作 小组成员 昨天完成的工作 今天计划完成的工作 李志霖 继续访问用户以深入了解他们的需求,分别采用面访,qq等不同方式对意见进行了采集,面访了30个人,qq空间以链接的 ...
- hubilder打包+C#服务端个推服务实现
关于推送鼓捣了好长时间,这里不再写helloworld了,只讲里面遇到的问题. 1.关于苹果开发者平台上的注册 网上很多的教程,只要按照步骤来设置就行了,在 iOS证书(.p12)和描述文件(.mob ...
- Ntfs 下的链接符号创建
熟悉过 Unix/Linux 都应该知道,Unix/Linux 用 ln 建立硬链接,ln -s 建立软链接(符号链接). 硬链接和符号链接的区别 Ntfs下的也有链接符: 内置命令:mklink ...
- 20155323刘威良《网络对抗》Exp3 免杀原理与实践
20155323刘威良<网络对抗>Exp3 免杀原理与实践 实践内容 1 正确使用msf编码器,msfvenom生成如jar之类的其他文件,veil-evasion,自己利用shellco ...
What is the !! (not not) operator in JavaScript? 解答1 Coerces强制 oObject to boolean. If it was falsey ...
From the JavaScript Reference on MDC, ~ (Bitwise NOT) Performs the NOT operator on each bit. NOT a y ...
Sometimes we might want to make a function more generic by having it accept a union of different typ ...
原文:http://www.cnblogs.com/yanhaijing/p/3685304.html 这是我所知道的最完整最简洁的JavaScript基础教程. 这篇文章带你尽快走进JavaScri ...
Are you baffled(阻碍:使迷惑) by the new operator in JavaScript? Wonder what the difference between a func ...
这是我所知道的最完整最简洁的JavaScript基础教程. 这篇文章带你尽快走进JavaScript的世界——前提是你有一些编程经验的话.本文试图描述这门语言的最小子集.我给这个子集起名叫做“Java ...
原文地址:http://www.2ality.com/2012/09/expressions-vs-statements.html Update 2012-09-21: New in Sect. 4: ...
javascript prototype原型链的原理 说到prototype,就不得不先说下new的过程. 我们先看看这样一段代码: <script type="text/javasc ...
js小技巧 每一项都是js中的小技巧,但十分的有用! 1.document.write(""); 输出语句 2.JS中的凝视为// 3.传统的HTML文档顺序是:documen ...
- 查看LINUX进程内存占用情况
可以直接使用top命令后,查看%MEM的内容.可以选择按进程查看或者按用户查看,如想查看oracle用户的进程内存使用情况的话可以使用如下的命令: (1)top top命令是Linux下常用的性能分析 ...
- guacamole 0.9.9安装与配置
以下命令很多都需要管理权限,建议使用管理员账号执行,遇到问题可以留言. 1.首先需要安装guacamole所需要的依赖库 必需安装的库有:Cairo.libjpeg-turbo.libpng.OSSP ...
- codeforces 333B - Chips
注意:横向纵向交叉时,只要两条边不是正中的边(当n&1!=1),就可以余下两个chip. 代码里数组a[][]第二维下标 0表示横向边,1表示纵向边. #include<stdio.h& ...
- HDU 4135 Co-prime
思路:直接用求(b,1)范围内互质的数,(a-1,1)范围内互质的数.再求反 就是敲一下容斥模板 #include<cstdio> #include<cstring> #inc ...
- SLC和MLC闪存芯片的区别
许多人对闪存的SLC和MLC区分不清.就拿目前热销的MP3随身听来说,是买SLC还是MLC闪存芯片的呢?在这里先告诉大家,如果你对容量要求不高,但是对机器质量.数据的安全性.机器寿命等方面要求较高,那 ...
- 转:如何让LoadRunner实现多个场景运行?
场景分析: 有3个不同的场景,分别为搜索,下载,上传,其中3个场景执行顺序为按照搜索->下载->上传流程操作:哪么如何让Loadrunner中如何实现多个场景运行: 方法1:利用Loadr ...
- 【Alpha】第一次项目冲刺
今日站立式会议照片 每个人的工作 小组成员 昨天完成的工作 今天计划完成的工作 李志霖 继续访问用户以深入了解他们的需求,分别采用面访,qq等不同方式对意见进行了采集,面访了30个人,qq空间以链接的 ...
- hubilder打包+C#服务端个推服务实现
关于推送鼓捣了好长时间,这里不再写helloworld了,只讲里面遇到的问题. 1.关于苹果开发者平台上的注册 网上很多的教程,只要按照步骤来设置就行了,在 iOS证书(.p12)和描述文件(.mob ...
- Ntfs 下的链接符号创建
熟悉过 Unix/Linux 都应该知道,Unix/Linux 用 ln 建立硬链接,ln -s 建立软链接(符号链接). 硬链接和符号链接的区别 Ntfs下的也有链接符: 内置命令:mklink ...
- 20155323刘威良《网络对抗》Exp3 免杀原理与实践
20155323刘威良<网络对抗>Exp3 免杀原理与实践 实践内容 1 正确使用msf编码器,msfvenom生成如jar之类的其他文件,veil-evasion,自己利用shellco ...








