Explore the true meaning of JavaScript logical operators (and, OR)

Source: Internet
Author: User
Tags logical operators

More than half of the December, Winter is a wonderful season, the cold air forcing people to hide in a comfortable environment to live. Winter will give a quiet and peaceful atmosphere, let people immersed in it, as if the end of an old stage, but also a new stage of the beginning. So, the western and Chinese Christmas and Spring Festival are chosen in winter is not unreasonable, in the coldest time of the year, people clustered in the warm environment, each other to tell each other the past year of their achievements, looking forward to the New Year's good wishes, mutual care of the reunion, The cold of the weather and the warmth of human kindness formed a strong contrast. And in the cold, as if more conducive to people to think, to explore the true meaning of knowledge.

This time want to share is JS in the logical operators and, or, that is, && , | | , new students see here will feel uninteresting, this thing has what good to share, just started to learn JS when not will it? I've used it countless times without any problems. and experienced students may be immersed in meditation, it is difficult to find out what the secret lies in it? Yes, don't look at this simple few operators, although this is the most basic knowledge, but the hidden mysteries are very intriguing, then I will be for you to uncover the simple answer to the magic behind the operator.

The role of the foundation I will not say, these two symbols are a programmer can understand, here first I would like to first say that the implicit conversion of JS.

As we all know, JS will automatically convert the value of non-Boolean type to the value of Boolean type and then perform the logical operation when making logical judgment. In the beginner JS, will be talked about in the implicit conversion, in addition to a few specific false values, the other will be converted to true value, these false values are:

1 Nan;2 ""; 3 undefined;4 null;5 0;

With these implicit conversion rules, it forms the core basis of the logic operation in JS.

In fact, in JS, to say "logical operator" is not exactly correct, Kyle Simpson in the "you Don T Know JS" series, said: "Not so much as the ' logical operator ', rather than the ' selector operator ." "Why did the master say so?" In fact, most of us are blinded by the appearance of JS, such as the following a very simple code:

1 if ("Hello" && 0) {2     Console.log (TRUE); 3} else {4     console.log (FALSE); 5}

If you do not understand the depth of JS, you may explain this code: first in the logical judgment, "Hello" is a truth, 0 is a false value, a truth and a false value for the operation, the result is false. This may also be the understanding of most people, but in fact, its internal principles can be more than that simple, because && and | | The return is not the true or false of the judging condition, but a primitive value in the judging condition. It will judge the value in the conditional judgment in turn, if it is a non-boolean value, then convert it to a Boolean, then decide which value to return based on the condition of the judgment.

For &&: The operator returns the first false value in a conditional statement, and if all the values are true, the last value,&& is also known as the "daemon operator." For example, the following section of code:

1 var a = "Hello" && "World"; 2 Console.log (a);  world3 var b = 0 && 1;4 console.log (b);  0

As you can see, the logical operator actually returns not the true or false condition, but the original value. If there are more than one && operator in the conditional statement, follow the above principles, judging from left to right, and return the false value if all values are true, and return the last value.

for | | : This operator, in contrast to the && operator, returns the first true value in a conditional statement, and returns the last if all values are false. For example, the following section of code:

1 var a = "Hello" | | 0;2 Console.log (a);  Hello3 var b = 0 | | Nan;4 Console.log (b);  NaN

Similarly, | | Returned is not a Boolean value. If there are multiple | | Follow the same principle and scan from left to right.

Here also came to the core of this article, in JS, conditional judgment statements are built on the implicit conversion, that is, the so-called logical operators, in fact, in the conditional judgment statement from left to right scanning, if it is a Boolean value, then judge the true and False Boolean value, if it is a non-boolean value, Then the value of the implicit conversion, and then determine the true and false, if the condition is satisfied, then return the value, if not meet the condition value, then return the last value, and then in the return of the value to be judged, if it is a Boolean value, then directly judge, if it is a non-boolean value, then the implicit conversion to a Boolean value So we can also refer to && as "take the dummy operator" , put | | Called the "take a true operator" because both operators are essentially the first true or false value in a conditional statement, and if they are not always found, the last value is returned. And such an algorithm just satisfies the logic of the demand, such as the && operator, if all values are true, then the return of which value does not matter, because all the value can be implicitly converted to true, and as long as there is a false value, the judgment condition is not true, so it will return the first encountered false value. and | | operator, if all values are false values, any return will be implicitly converted to false, but if a true value is encountered, the condition is determined, so the first truth encountered is returned. && | | Operators are "short-circuited".

So we can implement a function of a logical operation by ourselves:

1//&& equivalent to: 2 function and () {3 for     (var i = 0; i < arguments.length; i++) {4         if (!arguments[i]) { 5             return arguments[i]; 6         } 7     } 8     return arguments[i-1]; 9}10 11//| | Equivalent to: n-function OR () {     var i = 0; i < arguments.length; i++) {         if (Arguments[i]) {             arguments[i];16         }17     }18     return arguments[i-1];19}

(Note: I also want to be right here!) This operator is explained, but given the content and length of the problem, temporarily do not do in-depth exploration, only to do simple narration. Operators actually run mechanisms with && and | | Is the same, first the parameter value is judged, if it is a Boolean value, then the inverse operation, if it is a non-boolean value, the first implicit conversion, and then take the inverse operation. And we usually write if (something) statements, actually mean if (!!). Something))

Then we can use this:

1 var a = ["Hello", Undefined, "World"];2 console.log (and.apply (null, a));  undefined3 var b = ["", 0, Nan];4 console.log (or.apply (null, b));  NaN

And then we can deduce the conclusion:

1 A = x | | Y;2//equivalent to: 3 A = x? x:y; 4 5 A = x && y;6//equivalent to: 7 a = x? y:x;

This is often what some compression tools do, as much as possible to convert complex conditional judgments into && or | | , because the code is more streamlined, but the readability is less significant.

For the first piece of code:

1 if ("Hello" && 0) {2     Console.log (TRUE); 3} else {4     console.log (FALSE); 5}

Now we're going to explain this: first, this is an operator, and the operator is to take the first false value, and if all the values are true, then the last value is returned. So in this statement, the first value is "Hello", because the value is a non-boolean value, the JS engine will first implicitly convert it to a Boolean value, and the value is not in the range of false values, so it will be converted to true. Then the JS engine will continue to find, the second value is 0, the value is also not a Boolean value, so the JS engine will also be implicitly converted to a Boolean value, and the value in the range of false values, so will be converted to false, meet the && operator's lookup criteria, the value 0 is returned. The conditional judgment statement accepts a value of 0, which is not a Boolean value, so it is implicitly converted, and the value is within the range of false values, so it is converted to false, and then the console outputs false.

So say later when we see && and | | Time, do not just the literal meaning to understand, after reading this article, you can be very proud to say to others, you really can use logical operators?

Well, just so many two little things behind also have so much essence, it seems that the depth of knowledge is endless, winter is really a can cause people to think of the season. Christmas is coming, I wish you a Merry Christmas here in advance, Merry christmas!

Explore the true meaning of JavaScript logical operators (and, OR)

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.