Arithmetic priority problems in JavaScript

Source: Internet
Author: User

Priority-Raised issues

This article summarizes the operators in JavaScript, many of whom have a knowledge point about operator precedence. This leads to the writing of some of the more wonderful JS code, you do not know what its output is, the following example.

var a = "hello";console.log("This is " + (a== "hello") ? ‘Mine‘ : ‘Yours‘);

JS code is as follows, what is the result of output in console?

Look at the topic and take it for granted. The option to output the result is: This is Mine . After the election, there is a little doubt about their answers. How can the answer be so straightforward, there must be something fishy about it. Then began to think carefully, found that the original set so deep. After analysis, this question is the precedence of the operator. According to the priority of the No, the following steps to answer the above topic:
The first step: the parentheses change precedence, so the values inside the parentheses are calculated to get the result:“This is ” + true ? ‘Mine‘ : ‘Yours’
The second step: + the priority is higher ?: , so first count + number, get the result:“This is true" ? ‘Mine‘ : ‘Yours’
Part III: Calculation ? : because the preceding string is not empty, the conversion to bool value is true , therefore, the result of the entire expression is Mine ;

After the above analysis, the answer to this question is Mine . I hope that after encountering this kind of exotic writing statement, careful analysis, as far as possible to avoid into the pit. The following summarizes the precedence of the operations in JS.

Summary of priority levels

The following table lists the JavaScript operators by priority from highest to lowest. Operators with the same precedence are evaluated in order from left to right.

Arithmetic priority problems in JavaScript

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.