shorthand trick with boolean expressions
https://stackoverflow.com/questions/2802055/what-does-the-construct-x-x-y-mean
--------------------------------------------------------
What is the double pipe operator (||
)?
The double pipe operator (||
) is the logical OR
operator . In most languages it works the following way:
- If the first value is
false
, it checks the second value. If it'strue
, it returnstrue
and if it'sfalse
, it returnsfalse
. - If the first value is
true
, it always returnstrue
, no matter what the second value is.
So basically it works like this function:
function or(x, y) {
if (x) {
return true;
} else if (y) {
return true;
} else {
return false;
}
}
If you still don't understand, look at this table:
| true false
------+---------------
true | true true
false | true false
In other words, it's only false when both values are false.
How is it different in JavaScript?
JavaScript is a bit different, because it's a loosely typed language. In this case it means that you can use ||
operator with values that are not booleans. Though it makes no sense, you can use this operator with for example a function and an object:
(function(){}) || {}
What happens there?
If values are not boolean, JavaScript makes implicit conversation to boolean. It means that if the value is falsey (e.g. 0
, ""
, null
, undefined
(see also All falsey values in JavaScript)), it will be treated as false
; otherwise it's treated as true
.
So the above example should give true
, because empty function is truthy. Well, it doesn't. It returns the empty function. That's because JavaScript's ||
operator doesn't work as I wrote at the beginning. It works the following way:
- If the first value is falsey, it returns the second value.
- If the first value is truthy, it returns the first value.
Surprised? Actually, it's "compatible" with the traditional ||
operator. It could be written as following function:
function or(x, y) {
if (x) {
return x;
} else {
return y;
}
}
If you pass a truthy value as x
, it returns x
, that is, a truthy value. So if you use it later in if
clause:
(function(x, y) {
var eitherXorY = x || y;
if (eitherXorY) {
console.log("Either x or y is truthy.");
} else {
console.log("Neither x nor y is truthy");
}
}(true/*, undefined*/));
you get "Either x or y is truthy."
.
If x
was falsey, eitherXorY
would be y
. In this case you would get the "Either x or y is truthy."
if y
was truthy; otherwise you'd get "Neither x nor y is truthy"
.
The actual question
Now, when you know how ||
operator works, you can probably make out by yourself what does x = x || y
mean. If x
is truthy, x
is assigned to x
, so actually nothing happens; otherwise y
is assigned to x
. It is commonly used to define default parameters in functions. However, it is often considered a bad programming practice, because it prevents you from passing a falsey value (which is not necessarily undefined
or null
) as a parameter. Consider following example:
function badFunction(/* boolean */flagA) {
flagA = flagA || true;
console.log("flagA is set to " + (flagA ? "true" : "false"));
}
It looks valid at the first sight. However, what would happen if you passed false
as flagA
parameter (since it's boolean, i.e. can be true
or false
)? It would become true
. In this example, there is no way to set flagA
to false
.
It would be a better idea to explicitly check whether flagA
is undefined
, like that:
function goodFunction(/* boolean */flagA) {
flagA = typeof flagA !== "undefined" ? flagA : true;
console.log("flagA is set to " + (flagA ? "true" : "false"));
}
Though it's longer, it always works and it's easier to understand.
You can also use the ES6 syntax for default function parameters, but note that it doesn't work in older browsers (like IE). If you want to support these browsers, you should transpile your code with Babel.
See also Logical Operators on MDN.
shorthand trick with boolean expressions的更多相关文章
- POJ | Boolean Expressions
总时间限制: 1000ms 内存限制: 65536kB 描述The objective of the program you are going to produce is to evaluate ...
- Boolean Expressions POJ - 2106 (表达式求值)
The objective of the program you are going to produce is to evaluate boolean expressions as the one ...
- [poj 2106] Boolean Expressions 递归
Description The objective of the program you are going to produce is to evaluate boolean expressions ...
- Boolean Expressions
Boolean Expressions Time Limit: 1000MS Memory Limit: 30000K Description The objective of the ...
- POJ 2106 Boolean Expressions
总时间限制: 1000ms 内存限制: 65536kB 描述 The objective of the program you are going to produce is to evaluate ...
- (栈的应用5.2.2)POJ 2106 Boolean Expressions(表达式求值)
/* * POJ_2106.cpp * * Created on: 2013年10月30日 * Author: Administrator */ #include <iostream> # ...
- POJ 2106 Boolean Expressions (布尔表达式求值)
题意:关于!,&,| 的运算,表达式中V代表true,F代表false. 思路:见代码吧,很详细了. 要注意 !!!F,!(...) 的情况. #include <iostream> ...
- poj 2106 Boolean Expressions 课本代码
#include<cstdio> const int maxn=100 +10; int val[maxn],vtop; int op[maxn],otop; void insert(in ...
- POJ 2106-Boolean Expressions,双栈运用类似表达式求值!
Boolean Expressions 首先声明此题后台可能极水(毕竟这种数据不好造!).昨天写了一天却总是找不到bug,讨论区各种数据都过了,甚至怀疑输入有问题,但看到gets也可以过,难道是思路错 ...
随机推荐
- 搭建openstack系统初始化(2)
操作系统环境 :Centos 7.3 x64 1).安装需要的包 yum install wget vim chrony net-tools bash-completion -y 2)配置阿里elpl ...
- centos6.9 部署wordpress
用centos6.9搭建wordpressLinux.Nginx.Mariadb(Mysql).PHP 1 yum install nginx mariadb php php-fpm php-mysq ...
- PHP的命名空间namespace
对于命名空间,官方文档已经说得很详细[查看],我在这里做了一下实践和总结. 命名空间一个最明确的目的就是解决重名问题,PHP中不允许两个函数或者类出现相同的名字,否则会产生一个致命的错误.这种情况下只 ...
- CodeForces 731E Funny Game
博弈,$dp$. 设$f[i]$表示 如果先手第一次出手取到位置$i$,直到游戏结束,双方均采取最优策略,先手-后手得分的差值. 那么$f[i]=min(sum[i]-sum[j]+maxf[j+1] ...
- 洛谷P3216 [HNOI2011] 数学作业 [矩阵加速,数论]
题目传送门 数学作业 题目描述 小 C 数学成绩优异,于是老师给小 C 留了一道非常难的数学作业题: 给定正整数 N和 M,要求计算 Concatenate (1 .. N)Mod M 的值,其中 C ...
- 洛谷——P1927 防护伞
P1927 防护伞 题目描述 据说 2012 的灾难和太阳黑子的爆发有关.于是地球防卫小队决定制造一个特殊防护 伞,挡住太阳黑子爆发的区域,减少其对地球的影响.由于太阳相对于地球来说实在是太 大了,我 ...
- 进入CentOS7紧急模式恢复root密码
第一步.重启CentOS7,在以下界面选择要编辑的内核(一般第一个),按e进入编辑界面 第二步.在编辑界面找到如下一行,将ro改为rw init=/sysroot/bin/sh.改完后<Ctrl ...
- Hive 空指针(NPE)异常
空指针NullPointerException 1 Hive之前的一些BUG [HIVE-9430] - NullPointerException on ALTER TABLE ADD PARTITI ...
- cogs 2039. 树的统计
2039. 树的统计 ★★ 输入文件:counttree.in 输出文件:counttree.out 简单对比时间限制:1 s 内存限制:128 MB [题目描述] 关于树的统计问题有 ...
- BZOJ 4884 [Lydsy2017年5月月赛]太空猫(单调DP)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=4884 [题目大意] 太空猫(SpaceCat)是一款画面精致.玩法有趣的休闲游戏, 你 ...