JS and OR operator | | Introduction to && Usage

Source: Internet
Author: User
Tags bitwise bitwise operators logical operators

1. Logic or operator | | :

Because of && and | | The second operand may not be considered, so we should try to avoid using expressions with side effects (assignment, increment, decrement, and function calls) on their right side unless we know exactly what we are doing.

The code is as follows Copy Code


if ((a = = null) && (b++ >10)) stop (); b++ increment operation may not be performed
if ((b++ >10) && (a = = null)) stop (); Guaranteed b++ increment operations are performed

2. Bitwise operation

& and | In addition to "logical operations" [1], you can also perform bitwise operations, while && and | | Only logical operations can be performed.

3.JS & and | with C # & and |

,& and | In JS are just bitwise operators, while in C #,& and | are both logical operators and bit operations, as can be seen from the following code.

The code is as follows Copy Code


Document.Write (True & false); JS, the result is 0

document.write (1 & 0); JS, the result is 0
BOOL A = true & false; C #, the result is false
int b = 1 & 0; Result is 0

When operator | | Of the two operands is a Boolean value that performs a Boolean or operation on both counts.

It first calculates the first operand, and if the value of the expression can be converted to true, it returns the value of the expression on the left. Otherwise calculate the second op count even if | | The operator's operand is not a Boolean, and it can still be treated as a Boolean or operation, because it can be converted to a Boolean value regardless of the type of value it returns.

On the other hand, the number of operations for a non-boolean is used | |, which uses the attribute it returns to a value that is not Boolean. This use of this operator is typically to select the first defined and Non-null value in a set of alternative values (that is, the first value that is not converted to false)

Cases:

The code is as follows Copy Code
var Max=max_width | | Preferences.max_width | | 500

Cases:

The code is as follows Copy Code

var add_level = 0;

Switch (add_step) {

Case 5:add_level = 1;

Break

Case 10:add_level = 2;

Break

Case 12:add_level = 3;

Break

Case 15:add_level = 4;

Break

Default:add_level = 0;

Break

}

What would it be like to use this piece of code?

OK, let's take a look at JS strong expressiveness bar:

The code is as follows:

The code is as follows Copy Code

var add_level = (add_step==5 && 1) | | (add_step==10 && 2) | | (add_step==12 && 3) | | (add_step==15 && 4) | | 0;

More powerful, and more gifted:

The code is as follows:

The code is as follows Copy Code

var add_level={' 5 ': 1, ' Ten ': 2, ' ': 3, ': 4}[add_step] | | 0;

Second requirement:

The code is as follows:

The code is as follows Copy Code

var add_level = (add_step>12 && 4) | | (add_step>10 && 3) | | (add_step>5 && 2) | | (add_step>0 && 1) | | 0;

First we comb a concept, please remember: in the JS logical operation, 0, "", null, False, undefined, Nan will be sentenced to false, the others are true (as if there is no omission, please confirm).

This must be remembered, otherwise apply | | And && there will be problems.

Here by the way: I am often asked to see a lot of code if (!! attr), why not directly write if (attr);

In fact, this is a more rigorous formulation:

Please test typeof 5 and typeof!! 5 the difference.!! The role is to convert a variable of another type into a bool type.

The following main discussion of the following logical operators && and | |.

In almost all languages | | And && all follow the "short-circuit" principle, such as the first expression in && is not to deal with the second expression, and | Just the opposite.

JS also follows the above principles. But what's more interesting is the value they return.

Code: var attr = True && 4 && "AAA";

Then the result of the run attr is not simple true or false, but "AAA"

Take another look at | | :

Code: var attr = attr | | ""; This operation is often used to determine whether a variable is defined, and if it is not defined, give him an initial value, which is useful when defining a default value for a function's parameters. Because JS is not like PHP, you can define func ($attr =5) directly on the type parameter. Again, remember the principle: if the argument needs to be 0, "", null, False, undefined, Nan, it will also be treated as false.

The code is as follows Copy Code

if (a >=5) {

Alert ("Hello");

}

Can be written as:

A >= 5 && alert ("Hello");

This is done with just one line of code. But the point to note is: JS in | | And && features help us streamline code while also bringing down code readability. It's up to us to weigh it.

On the one hand, the streamlining of JS code, can substantially reduce network traffic, especially the large number of applications of the JS Public Library. The personal comparison recommendation is: if it is a relatively complex application, please write some comments appropriately. This is the same as the expression, the ability to streamline the code, but the readability will be reduced, the people who read the code will be higher, the best way is to write a note.

We can not use these techniques, but we must be able to understand, because these techniques have been widely used, especially like jquery and other JS box code, do not understand these you are difficult to understand other people's code.

Like the var yahoo = Yahoo | | {}; This is very widely used.

OK, finally let's take a look at the code in jquery:

The code is as follows:

The code is as follows Copy Code

var wrap =
!tags.indexof ("<opt") && [1, "<select multiple= ' multiple ' >", "</select>"] | |

!tags.indexof ("<leg") && [1, "<fieldset>", "</fieldset>"] | |

Tags.match (/^< (THEAD|TBODY|TFOOT|COLG|CAP)/) && [1, "<table>", "</table>"] | |

!tags.indexof ("<tr") && [2, "<table><tbody>", "</tbody></table>"] | |

(!tags.indexof ("<td") | | |!tags.indexof ("<th")) && [3, "<table><tbody><tr>", "</tr ></tbody></table> "] | |

!tags.indexof ("<col") && [2, "<table><tbody></tbody><colgroup>", "</colgroup ></table> "] | |

IE can ' t serialize <link> and <script> tags normally
!jquery.support.htmlserialize && [1, "div<div>", "</div>"] | | [0, "", ""];

Go to HTML and back, then peel off extra wrappers
div.innerhtml = wrap[1] + elem + wrap[2];

Move to the right depth
while (wrap[0]--)
div = div.lastchild;

This code is used by the author when dealing with $ (HTML), some tags must be bound, such as <option> must be within the <select></select>

Some foreign reference

The basic theory
In Boolean logic, a statement can have two values, true or FALSE. When using Boolean logic in philosophy, the statement can is a sentence, like

It rains today.
In the more down-to-earth applications like JavaScript, a statement are something like

The code is as follows Copy Code
x = = 4

Both statements can be either true or false. When writing a The It is often necessary to the if a statement is true or false. Usually this are done by an if () statement. If the statement x = = 4 is true, then do something:

The code is as follows Copy Code
if (x==4) {
Do something
}

All are not surprising. Boolean logic, however, also offers possibilities to evaluate a whole string of statements and, whether the whole Strin G is true or false. Like:

It rains today and my feet are getting wet
In Boolean logic, this longer statement be true if it rains today is true and I feet are getting wet is true.

It rains today OR my feet are getting wet
In Boolean logic, this statement is true if it rains the ' is ' true OR if your feet are getting wet is true OR if both stat Ements are true.

This is also very useful when writing programs. For instance, suppose your want to do something if x==4 OR y==1. Then You write:

The code is as follows Copy Code
if (x==4 | | y==1) {
Do something
}

The statement (x==4 | | y==1) is true if X is 4 OR y is 1.

And, OR and not
For JavaScript purposes, you need to know and, OR and not:

and (&&): True when both elements are true.
Example: (

The code is as follows Copy Code
X==4 && y==1).

OR (| |): True when at least one of the elements is True.
Example:

The code is as follows Copy Code
(x==4 | | y==1).

Not (!): This toggles a statement from true to false or from false to true.

The code is as follows Copy Code
Example: (x==4 | |!) ( y==1)).

This example was true if X is 4 OR y isn't 1.
Boolean logic also contains the XOR operator, which is true when exactly one statement was true (but not both). JavaScript doesn ' t support logical XOR.

When you are only two statements, the this are all easy. It gets more complicated if your want to use three or more statements, like:

The code is as follows Copy Code
if (x==4 && (!) Y==1) | | z==0) {
Do something
}

As in mathematics, the bit that's between the brackets () is evaluated a. So it example is true and the ' code is ' executed if X is 4 and (Y are not 1 or Z-is 0 or both).

Try it
At the sight this seems hideously complicated. I could go in writing more about how Boolean logic works, but it's better to try it for yourself.

In the table below you three statements, X, Y and Z. All of them can is either true or false. Fill in the and/or, the not ' s, where the brackets are and the value of X, Y and Z, then hit Boole () to "how your Statem ENT evaluates.

The code is as follows Copy Code

X. Y
X. Y). Z
X. Y. Z)
Not

X
True
False and
Or not

Y
True
False and
Or not

Z
True
False



Play around with it until for you, start to understand what it's all about. Later you might try to make a prediction before hitting Boole ().

Checking a variable
Above We have seen we can use Boolean logic into a statement like

The code is as follows Copy Code
if (x==4 && (!) Y==1) | | z==0) {
Do something
}

A second way to use Boolean logic are to? If something exists or not. For instance

The code is as follows Copy Code
if (!x) {
Do something
}

In this example the ' code is ' executed if X does not exist (X=false).
X is False

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.