|| and && usage in js

&& and || are especially widely used in the JQuery source code. I found some examples on the Internet as a reference, and studied their usage:

1. &&
function a(){
alert("a");
return true;
}
function b(){
alert("b");
return true;
}
var c=a()&&b();
alert(c);
  a() && b() : If it returns true after executing a(), execute b() and return the value of b; if it returns false after executing a(), the entire expression returns the value of a(), b( ) does not execute;

2. ||

function a(){
alert("a");
return true;
}
function b(){
alert("b");
return false;
}
var c=a()||b();
alert(c);
  a () || b() : If it returns true after executing a(), the entire expression returns the value of a(), and b() does not execute; if it returns false after executing a(), execute b() and return the value of b();

  && takes precedence over ||

  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 return 3 => 3 || 0 return 3 => 3&&4 return 4
  Statement ②: first execute 1&&3 return 3, after 0&&4 return 0, and finally execute the result comparison 3||0 return 3
  Statement ③: first Execute 0&&3 to return 0, execute 1&&4 to return 4, and finally execute the result comparison 0||4 to return 4

  Note: Integers other than 0 are true, undefined, null and the empty string "" are false.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325337072&siteId=291194637