JS logic or | Summary of the use of logic and & amp;, and the logic in js

Source: Internet
Author: User

JS logic or | Summary of logic and & usage, and logic in js

JS logic or | Summary of logic and & Usage
// 1. In the if judgment
// If (1 = 1 | 2 = 3) {}//-> if either of the two conditions is true, the whole is true "or"
// If (1 = 1 & 2 = 3) {}//-> both conditions are true, and the whole condition is true. "and"

// 2. When either of the two values is obtained
// 1 | 2-> 1 "logic or" First, check whether the value on the left is true or false. If it is true, the value on the left is returned, false returns the right value.

// 1 & 2-> 2 "logic and" First, check whether the value on the left is true or false. If it is true, the return value is the value on the right, false returns the value on the left.

// How to check whether it is true or false?
// Only 0, NaN, null, undefined, and null strings are false, and others are true.

// We apply logic or initialize data in real projects
// Requirement: Calculate the sum of two numbers. If the second number is not passed, we add zero by default.
Function sum (num1, num2 ){
// If (typeof num2 = "undefined") {//-> indicates that num2 has not passed the value. The default value is undefined. In this case, the value is changed to 0.
// Num2 = 0;
//}
Num2 = num2 | 0; //-> undefined | 0-> num2 = 0 is equivalent to the above judgment.
Console. log (num1 + num2 );
}
// Sum (100); //-> num1 = 100 num2 = undefined

// 3. When | and & appear at the same time, the priority of & is greater than |
Console. log (0 | 1 & 2 | 3 );
// 1 & 2-> 2
// 0 | 2-> 2
// 2 | 3-> 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.