If...else statement

Source: Internet
Author: User
Tags expression
Statement

Conditionally executes a set of statements based on the value of an expression.

if (condition)
   statement1

[else
statement2]

Parameters

Condition

Required option. A Boolean expression . If the condition is null or undefined, then condition is treated as false.

Statement1

Options available. The statement to execute when condition is true . Can be a compound statement .

Statement2

Options available. The statement to be executed when condition is false . Can be a compound statement.

Description

It is usually a good habit to enclose statement1 and statement2 in braces ({}), which is clearer and avoids inadvertent errors.

Example

In the following example, you might want to match the else to the first if statement, but it actually matches the second.

if (x == 5)   if (y == 6)      z = 17;else   z = 20;

Rewriting the code in the following way eliminates any ambiguity:

if (x == 5)   {   if (y == 6)      z = 17;   }else   z = 20;

Similarly, if you want to add a statement to statement1without using curly braces, you may have an error:

if (x == 5)   z = 7;   q = 42;else   z = 19;

In this case, there is a syntax error because there are more than one statement between the if and else statements. The statement between if and else requires curly braces.

Requirements

Version 1

Please see

Conditional operator (?:)



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.