An "if" statement is a flow control structure in most programming languages that branches execution flow depending on a binary condition, generally evaluated at runtime. If statements are also commonly also called conditionals. When using this tag please also include an appropriate language tag, such as e.g. "java" if your question is language-specific.
An if
statement is a flow control structure in most programming languages that branches execution flow depending on a binary condition, generally evaluated at runtime. If-statements are also commonly known as conditionals.
When using this tag please also include an appropriate language tag, such as e.g. java if your question is language-specific.
Basic Syntax
The if
statement has the following syntax:
if <condition>
then
<statement-1>
else
<statement-2>
<condition>
may be parenthesized (as it is in JavaScript), the keyword then
may be omitted (Python, C-like languages, JavaScript and others).
The else
section is optional in most languages.
An example if
statement in JavaScript:
var myVariable = 100;
if (myVariable >= 20) {
console.log('My variable is greater than or equal to 20!');
} else {
console.log('My variable is less than 20!');
}
if-else
statements may also be nested, where another if
may appear in if
statement, and/or in else
statement. For example:
if ( number1 > 20 )
if ( number2 > 50 )
print('Both numbers satisfy condition')
else
print('Second number doesn't satisfy condition')
else
if( number2 > 50 )
print('Only Second number satisfies condition')
else
print('None of the two numbers satisfy condition')
else+if
is used to chain if
statements:
if ( number > 20 )
print('Greater than 20')
else+if ( number > 10 )
print('Greater than 10')
else
print('Less than 11')
else+if
statements may simply be an else
statement followed by an if
(e.g else if
; done in JavaScript and many C-like languages), or a special keyword such as elif
(Python), or elsif
(Perl).
As a ternary operator
In C and C-like languages, conditional expressions can take the form of a ternary operator called the conditional expression operator, ?:
, which follows this template:
(condition)?(evaluate if condition was true):(evaluate if condition was false)
In Python, if
is used explicitly, and the ordering is slightly different:
(evaluate if condition was true) if (condition) else (evaluate if condition was false)
An example of the ternary operator in JavaScript:
var myVariable = 100;
myVariable>20 ? console.log('Greater than 20!') : console.log('Less than or equal to 20!');
See also: condition