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