Logical identifiers in JavaScript &&, | | With! Introduction of _javascript Skills

Source: Internet
Author: User

Like C, Java and other languages, JavaScript can use &&, | |,! Three logical judges to logically judge a Boolean value. Unlike C and Java, the logic in JavaScript (&&) and logic or (| |) The operator can be applied to any value, and it is not necessarily a Boolean value to return after the operation ends.

Rules for handling logic and &&

The processing rules for && in JavaScript are as follows:

1. Determine whether the first value is Falsy. If Falsy, the first value is returned directly (not necessarily a Boolean type).
2. If the first value is Truthy, the second value is returned directly (not necessarily a Boolean type).

Copy Code code as follows:

var o = {x:1, y:2};
Console.log (o && o.y);//2
Console.log (null && x);//null

Logic or | | The processing rules

Similar to the && operator, JavaScript | | The processing rules are as follows:

1. Determine whether the first value is truthy. If Truthy, the first value is returned directly (not necessarily a Boolean type).
2. If the first value is Falsy, the second value is returned directly (not necessarily a Boolean type).

|| This behavior of the operator makes some shortcuts in JavaScript a reality:

1. Get the first Truthy value from a series of values:

Copy Code code as follows:

var a = null;
var B = 42;
var v = a | | B | | 100;
Console.log (v);//42

2. Assign a default value to a parameter in a function:
Copy Code code as follows:

function Test (p) {
p = P | | {};//if P is isn't passed, make it a empty object.
}

With && and | | Different,! The behavior of the operator is consistent with languages such as C and Java, and only Boolean values (TRUE or FALSE) are returned.

Related Article

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.