Home > Web Front-end > JS Tutorial > body text

&& and || usage in JS

一个新手
Release: 2017-10-20 10:36:34
Original
2103 people have browsed it

Among the flow control statements, the one we are most familiar with is

 if( 条件 ){   //代码块  
 }else {   //代码块
 }
Copy after login

For a code that executes different code, if a lot of code is executed, it may be necessary to use the above method

But often during our development, we will encounter some assignment operations. If we use the above method, it will be too redundant.

For example:

 num1 = 10 num2 = 20
Copy after login

You can see that the above method only outputs a result, but uses five lines of code to implement it.

Next, we will witness how to use one line of code to replace the result achieved by the above five lines of code

 var num1 = 10; var num2 = 20; 
 // 第一种方式 也可以使用 三目运算符
 alert( num2 > mum1 ? num2 : num1 ); 
 //第二种方式  就是使用 && ,||
 alert( num2 > num1 && num2 || num1 );
Copy after login

The advantage of using &&,|| over ternary arithmetic is that it can judge multiple conditions , can also be used alone

Give an && example:

var num1 = 10;var num2 = 5;// 假如 num1,num2 都大于10 则输出 num1+num2;
   var result = num1>10 && num2 >10 && num1+ num2 || 0;
       alert(result);
Copy after login

Our developers know that during development, the data returned by reading the backend may not be read for some reason, then If the received data is an object, additional fields that have not been obtained will be added when receiving the field.

Take a || example:

var  reuslt = res && res.data || [];      
if ( result.length ) return;
Copy after login

Using this method, you can pass conditions Determine whether to use the variable. If it is an object, if it is not obtained and the object attribute is used, an error will be reported.

To avoid this pattern, you must judge, judge, judge when using it

The above is the detailed content of && and || usage in JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template