The function of the colon in JS

Source: Internet
Author: User
Tags case statement switch case

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

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.