Introduction to Boolean operator use in JS _javascript tips

Source: Internet
Author: User
Before we discussed the Boolean operators && and | | , I said that their result is a Boolean value. It's a bit simplistic to say. If you use them to compute Boolean data types, they do return Boolean values. But they can also be used to compute other types of data, at which point the return will be one of the parameters.

Or operator "| |" The real thing to do is this: it first checks its left parameter, and if it converts to a Boolean-type value, returns the argument to the left, or the right argument. Think about this when the operator is both on both sides of a Boolean type value. Why does it run like this? The result of this operation is actually very practical. Let's look at this example:
Copy Code code as follows:

var input = prompt ("What is your name", "Kilgore Trout");
alert ("OK Hello" + (Input | |) Dear "));

If the user presses "Cancel" or simply turns off the prompt dialog box, the input value will be null or "". In either case, the value converted to a Boolean type is false. Then input | | "Dear" This expression means that input has a value when the value of input, or get "dear". This is a very simple way to provide a default value.

The operator "&&" works like this, but it's the opposite of "| |". When its left argument converts a Boolean to a value of "false", it returns that value, otherwise it returns the value on the right. Another feature of the two operators is that the value of the expression on the right is evaluated only when necessary. On the true | | X "In this expression, no matter what x is, the result is true, so X is not computed, and if X has other effects, the effect is not generated." "False && X" is the same reason.
Copy Code code as follows:

False | | Alert ("I ' m happening!");
true | | Alert ("Not me.");

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.