A For loop without curly braces (curly braces) can also be executed correctly

Source: Internet
Author: User

Code One

The For loop has no {} curly braces (curly braces), and a statement below the for statement.

 for (var i=0;i<3;i++) console.log (1,i);

The above code can be output without error:

1 0
1 1
1 2

Code two

So, what if there are multiple lines in the For loop without curly braces?

 for (var i=0;i<3;i++) console.log (1, i); Console.log (2)

Output:

1 0
1 1
1 2
2

He would not cycle the second line.

Code Three

 for (var i=0;i<3;i++) console.log (1,i); Console.log (2) Console.log (3)

What if there are multiple statements and multiple lines of statements under the For loop?

1 0
1 1
1 2
2
3

Only the first statement is executed.

If

if (true) Console.log (1) Console.log (2)//1//2if( False) Console.log (1) Console.log (2)//2

Obviously, if is also the case.

While

 while (true) Console.log (1)

I was embarrassed to do that for a moment.

Conclusion:

In most programming languages, you can omit curly braces if there is only one statement in the contents of an if, for, and while statement.

Note: Is a statement , not a line.

For example, JS with a semicolon, the expression of a statement, so the above example, although the two statements on the same line, but only loop the previous statement.

A For loop without curly braces (curly braces) can also be executed correctly

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.