Home > Article > Web Front-end > Usage records of operators && and || in js_Basic knowledge
These two operators are often used and always confused, so record them. . .
a() && b(): If true is returned after executing a(), then b() is executed and the value of b is returned; if false is returned after executing a(), the entire expression returns the value of a() , b() is not executed;
a() || b(): If true is returned after executing a(), the entire expression returns the value of a(), and b() is not executed; if false is returned after executing a(), b() is executed and Return the value of b();
&& has higher priority than ||
The code is as follows
alert((1 && 3 || 0) && 4); //Result 4 ①
alert(1 && 3 || 0 && 4); //Result 3 ②
alert(0 && 3 || 1 && 4); //Result 4 ③
Analysis
Statement ①: 1&&3 returns 3 => 3 || 0 returns 3 => 3&&4 returns 4
Statement ②: Execute 1&&3 first to return 3, then execute 0&&4 to return 0, and finally compare the execution results with 3||0 to return 3
Statement ③: Execute 0&&3 first to return 0, then execute 1&&4 to return 4, and finally compare the execution results with 0||4 to return 4
Note: Non-zero integers are all true, undefined, null and empty string "" are false.