Speaking of this topic, let's start by discussing a question with a friend today. {A:1,b:2} will error directly in console output "uncaught syntaxerror:unexpected token:"; At first I could not understand, a normal object, why will the error? In fact, the analysis will know that {} in JS in addition to the object direct volume, but also represents the statement block; If a statement starts with "{", the JS engine resolves the {} to a statement block, so {a:1,b:2} is not parsed as an object, but is parsed for the statement a:1,b:2.
Analysis here, seems to have nothing to do with the topic, and at first thought that the discussion ended, but when the test {a:1}, the console will output 1, rather than error. Why is it? What does a:1 mean when it is treated as a statement? So the problem above should be more than just being parsed into a block of statements so simple.
Below we go to the point, as the title, we want to analyze the function of the colon in JS, I believe that the people who have learned JS are commonly used to the colon where there are three places, respectively: 1) a? B:C ternary operator; 2) switch case statement; 3) The direct amount of the object; Obviously the above problem is not related to the three. What does a colon do except for these three usages? In fact, the colon in JS also has a less common use, that is, the label statement. In JS, any statement can be tagged with a marker and a colon before it: identifier:statement so that it can be used anywhere, most commonly in a for loop.
Now back to the problem of initial error, through the analysis of the function of the colon is finally available, {A:1,b:2} runs alone is equivalent to a: (1,b:2), the parentheses in the statement resulting in an error.
Note: This article is only as a simple record in the learning process, if you have any questions please put forward and advise.
The function of the colon in JS