JavaScript type conversion: (true && 1) vs (true | | 1)

吃可爱长大的小学妹 提交于 2019-11-28 09:07:03

Check Douglas Crockford's site, it says:

The && operator is commonly called logical and. It can also be called guard. If the first operand is false, null, undefined, "" (the empty string), or the number 0 then it returns the first operand. Otherwise, it returns the second operand. This provides a convenient way to write a null-check:

var value = p && p.name; /* The name value will only be retrieved from
p if p has a value, avoiding an error. */

The || operator is commonly called logical or. It can also be called default. If the first operand is false, null, undefined, "" (the empty string), or the number 0, then it returns the second operand. Otherwise, it returns the first operand. This provides a convenient way to specify default values:

value = v || 10; /* Use the value of v, but if v doesn't have a value,
use 10 instead. */

To quote MDC;

&&; Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
||; Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

So in the first example, 1 is being returned because expr1 cannot be converted to false.

In the second example, true can be converted to true, so it's returned.

This has nothing to do with type conversion.

|| returns the first truthy operand. 1 || true will give you 1

&& returns the first falsy operand, or the second operand if both are truthy.

See page 58 of the ECMAScript specification

true && 1 => this will always return the last value of && if all conditions are true or false otherwise

true || 1 => this will always return the first 'truthy' value

Resources:

http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf

You can do other things too like:

var myVar = Math.random() > 0.5;

myVar && doFunc();

which is the same as

if(myVar) {
    doFunc();
}

The || basically means "If the first thing is false, go to second"

The && basically means "If the first thing is true, go to the second"

This is why you see things like this at the top of functions:

function myFunction(options) {
    options = options || {};
}

Which means: If options is falsey, make it {}

You're confusing casting (the * / + operators will do this) with logical evaluation (which &&, ||) do.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!