Three-layer understanding of || and && in js

||The use of && has three levels. Which one do you belong to?

1. Simple Boolean value judgment

	var res = true && false
	第一个操作数   第二个操作数     结果
	   true           false       false
	   true           true         true
	   false          false        false
	   false           true         true

2. The expression is converted to a Boolean value for a judgment (if and)

var a = 1;
var b = 2;
//如果a==3 并且b==2  那么就怎样怎样
var res =  a==3 && b==2  //false

3. Short-circuit operator (if so) (first make a judgment, and then run the following statement)

&& If the first number is already false, is it necessary to continue, obviously it is not necessary, because the result is already clear. But if the first number is true, then obviously the second number must be executed.

var a = 1;
var b = 2;
//如果a判断是1 是true那么就去执行将b重新赋值为10。   第一个数是判断 第二个是操作
a==1 && b=10  

❏ If the first operand is an object, the second operand is returned;
❏ If the second operand is an object, the object will only be returned if the evaluation result of the first operand is true ;
❏ If both operands are objects, return the second operand;
❏ If the first operand is null, return null;
❏ If the first operand is NaN, return NaN;
❏ If the first operand is NaN If an operand is undefined, return undefined.

4. Return value

According to the third fact, it can be known that its return value is not necessarily a boolean value, but depends on the expression executed later

In actual development, the return value of logical AND is not important, it is mainly used for judgment or short-circuit operation (judgment and run)

5. The second level of understanding of logical OR (or or)

6. The third level of understanding of logical OR (if nothing, then what) (mostly used for assignment)

多用于赋值
x= a || b

❏ If the first operand is an object, the first operand is returned;
❏ If the evaluation result of the first operand is false, then the second operand is returned;
❏ If both operands are objects, Return the first operand;
❏ If both operands are null, return null;
❏ If both operands are NaN, return NaN;
❏ If both operands are undefined, return undefined.
Similar to the logical AND operator, the logical OR operator is also a short-circuit operator. In other words, if the evaluation result of the first operand is true, the second operand will not be evaluated.

7. Priority of && || &&>||

a && b || c
如果a那么就执行b否则就执行c  也就是if   else  的缩写。通常用于执行语句
a是一个判断  b和c是语句

a ? b:c 通常赋值的用的

Guess you like

Origin blog.csdn.net/weixin_43131046/article/details/114628595