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's true, it returns true and if it's false, it returns false.
  • If the first value is true, it always returns true, 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""nullundefined (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 ifclause:

(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 flagAparameter (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的更多相关文章

  1. POJ | Boolean Expressions

    总时间限制: 1000ms  内存限制: 65536kB 描述The objective of the program you are going to produce is to evaluate ...

  2. Boolean Expressions POJ - 2106 (表达式求值)

    The objective of the program you are going to produce is to evaluate boolean expressions as the one ...

  3. [poj 2106] Boolean Expressions 递归

    Description The objective of the program you are going to produce is to evaluate boolean expressions ...

  4. Boolean Expressions

    Boolean Expressions Time Limit: 1000MS   Memory Limit: 30000K       Description The objective of the ...

  5. POJ 2106 Boolean Expressions

    总时间限制: 1000ms  内存限制: 65536kB 描述 The objective of the program you are going to produce is to evaluate ...

  6. (栈的应用5.2.2)POJ 2106 Boolean Expressions(表达式求值)

    /* * POJ_2106.cpp * * Created on: 2013年10月30日 * Author: Administrator */ #include <iostream> # ...

  7. POJ 2106 Boolean Expressions (布尔表达式求值)

    题意:关于!,&,| 的运算,表达式中V代表true,F代表false. 思路:见代码吧,很详细了. 要注意 !!!F,!(...) 的情况. #include <iostream> ...

  8. poj 2106 Boolean Expressions 课本代码

    #include<cstdio> const int maxn=100 +10; int val[maxn],vtop; int op[maxn],otop; void insert(in ...

  9. POJ 2106-Boolean Expressions,双栈运用类似表达式求值!

    Boolean Expressions 首先声明此题后台可能极水(毕竟这种数据不好造!).昨天写了一天却总是找不到bug,讨论区各种数据都过了,甚至怀疑输入有问题,但看到gets也可以过,难道是思路错 ...

随机推荐

  1. yii2-admin扩展自定义目录

    yii2-admin文件如下.仓库地址:  https://github.com/mdmsoft/yii2-admin/tree/master 复制yii2-admin文件至自定义目录 比如我就复制到 ...

  2. BZOJ 1901: Zju2112 Dynamic Rankings 区间k大 带修改 在线 线段树套平衡树

    之前写线段树套splay数组版..写了6.2k..然后弃疗了.现在发现还是很水的..嘎嘎.. zju过不了,超时. upd:才发现zju是多组数据..TLE一版才发现.然后改了,MLE...手写内存池 ...

  3. CentOS7.5安装teamviwer13

    1.首先到官网下载teamviewer13的rpm包 https://www.teamviewer.com/zhcn/download/linux/ 2.安装 安装依赖包 http://mirror. ...

  4. linux 把用户加入一个组&从这个组中移除

    # usermod -a -G www zhou // zhou这个用户现在属于两个组 zhou www # groups zhou zhou : zhou www # gpasswd -d zhou ...

  5. Codeforces 429 B. Working out-dp( Codeforces Round #245 (Div. 1))

    B. Working out time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...

  6. shell脚本--字符串处理和动态数组

    Linux下的文本处理命令,以清晰的列分割数据为高效处理源: awk 的gsub函数可替换指定字符串 echo "<tr><td>col1</td>< ...

  7. 手机发送验证码—.net代码

    注册过程中,短信发送验证码流程如下: (1).用户提交手机号码,申请湖区验证码 (2).网站按照预制规则生成验证码 (3).网站将用户手机号码和验证码发送到短信平台 (4).将制定内容发送到制定手机号 ...

  8. BZOJ2462[Beijing2011]矩阵模板(二维Hash)

    二维矩阵匹配问题,至今不知道Q的范围是多少,反正是要求做到读入复杂度. 二维Hash:就是一维的等效拓展,注意两维的Base不能相同. 其余就是一维Hash和二维前缀和的结合,可以自然溢出,据说概率很 ...

  9. [LOJ2553]暴力写挂

    锟题x2 以下用$a\rightarrow b$表示端点为$a,b$的链 把式子写成$(h_1(x)+h_1(y)-h_1(lca))-h_2(lca')$,第一部分就是$x\rightarrow r ...

  10. [xsy2238]snake

    题意:给定一条折线,问能否在不扭曲它的情况下让它完全通过一个小孔 这个条件就是:过折线上任意一点$x$存在一条直线把折线分成不与直线相交的两部分,换句话说存在(与折线只有一个交点$x$)的直线 结论是 ...