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也可以过,难道是思路错 ...
随机推荐
- AC日记——NOI2016区间 bzoj 4653
4653 思路: 线段树,指针滑动: 代码: #include <bits/stdc++.h> using namespace std; #define maxn 1000005 #def ...
- Oracle 数据库分页查询的三种方法
一.Oracle 数据库分页查询的三种方法 1.简介 不能对 rownum 使用 >(大于或等于 1 的数值).>=(大于 1 的数值).=(不等于 1 的数值),否则无结果.所以直接用 ...
- 【PHPExcel实例】 php 导出 excel 实例
CREATE TABLE `person` ( `) DEFAULT NULL, `name` ) DEFAULT NULL, `birthday` date DEFAULT NULL ) ENGIN ...
- 洛谷P1565牛宫
传送门:题目点这里; 首先理解题目,就是要求给定矩阵中权值和不小于零的最大子矩阵,数据范围200也还不算棘手,暴力n^4的算法也可以水到50分.正解要用到单调栈配合二分和前缀和,复杂度n^3logn, ...
- devops basic
- NGUI 简单的背包系统
1.首先在场景中创建格子,用来存放物体的 2.为每一个格子设置标签为Item,建议只做一个格子,然后创建预制体就可以了,然后为每一个格子附加Box Collider组件,要用于检测嘛, 3.接下来就是 ...
- 关于oracle存储过程需要注意的问题
在使用oracle存储过程时,有一些需要注意的地方,下面就来总结一下. 1.在oracle的存储过程中,数据表别名不能加as 也许是为了区分存储过程中的as,怕与过程中的as冲突. 如: select ...
- BZOJ 1982 [Spoj 2021]Moving Pebbles(博弈论)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1982 [题目大意] 两个人玩游戏. 每次任选一堆,首先拿掉至少一个石头, 然后移动任意 ...
- 【欧拉回路】【Fleury算法】CDOJ1642 老当益壮, 宁移白首之心?
题意: 构造一个01串,使得满足以下条件: 1. 环状(即首尾相连) 2. 每一位取值为0或1 3. 长度是2^n 4. 对于每个(2^n个)位置,从其开始沿逆时针方向的连续的n位01串(包括自己) ...
- B 君的第二题 (hongkong)
B 君的第二题 (hongkong) 题目大意: 一个长度为\(n(n\le2\times10^5)\)的数组,给定一个数\(k(k\le40)\).用\(a[i][j]\)表示该数组\(i\)次前缀 ...