Differences between JS &, | and | operators

Source: Internet
Author: User

1. Performance Comparison

If the first operation Number of & is false, false is directly returned without considering the second operation number. If | the first operation number is true, and returns true directly without considering the second operation. & And | the operator is not like this. They always have to compare two computations to get the result, so the performance is better than & and |.

Because & and | may not consider the second operation number, we should try to avoid using expressions with side effects (Value assignment, increment, decrease, and function call) on the right of them, unless you know exactly what you do.


If (a = null) & (B ++> 10) stop (); // the incremental operation of B ++ may not be executed
If (B ++> 10) & (a = null) stop (); // ensure that all incremental operations of B ++ are executed

2. bitwise operations

& | In addition to "logical operations" [1], you can also perform bit-by-bit operations, while & | you can only perform logical operations.

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

In JS, & and | are only bit-by-bit operators, while in C #, & and | are both logical operators and bitwise operations. You can see through the following 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; // The result is 0.


Note [1]: & and | this is a bit-by-bit operator, so you can perform "logical operations ", the reason is that JavaScript is a non-type language and data types can be freely converted. When "& |" is used for "logical operation", true is actually converted to 1, false is converted to 0, and then bitwise operations are performed. It is also because the & | Operator is a bit-by-bit operator that the result is obtained by comparing the numbers of two operations in the first vertex, this results in lower performance than & |.

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.