Promotic
WikipediaLinkedInYoutubeTwitterFacebook

if...else - statement of language JavaScript

Description:
Conditionally executes a group of statements, depending on the value of an expression.
Syntax:
if (condition) statements [else elsestatements];
 
or a simple conditional value assignment:
var variable = (condition) ? trueValue : falseValue ;
 
or, you can use the block form syntax:
if (condition)
{
  [statements]
}
[else if (condition-n)
{
  [else ifstatements]]
}
[else
{
  [elsestatements]]
}
 
condition A numeric or string expression that evaluates to true or false. If condition is Null, condition is treated as false.
statements One or more commands separated by semicolons that are executed if condition is true.
condition-n Same as condition
else ifstatements One or more statements executed if the associated condition-n is true.
elsestatements One or more statements executed if no previous condition or condition-n expression is true
Note:
You can use the single-line form (first syntax) for short, simple tests. However, the block form (second syntax) provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug.

Note With the single-line syntax, it is possible to have multiple statements executed as the result of an If...Then decision, but they must all be on the same line and separated by semicolons, as in the following statement:

if (a>10) {a=1; b=5; c=0;}
 
When executing a block (second syntax), the condition is tested. If the condition is true, then the following commands are executed. If the condition is false, then the else if blocks (if present) are evaluated. If the true condition is found, the following corresponding commands are executed. If none of the else if conditions is evaluated as true (or there is no else if block present), then the commands that follow after else are executed.

The else and else if blocks are both optional. You can have as many else if statements as you want in a block if, but none can appear after the else clause. The if commands can be nested, i.e. contained in another if commands.

 
It is also possible to use the single-line form of conditional assignment of value to a single varible.

If condition is evaluated as true, then the value written after the question mark is assigned. In other cases the value written after the colon is assigned

var b = a > 10 ? 1 : 0;
 
For similar purpose in the VBScript language is used the command If...Then...Else.
Example:
var Temperature;
...
if (Temperature>95)
{
  ...
}
else if (Temperature<12)
{
  ...
}
else
{
  ...
}
© MICROSYS, spol. s r. o.Tavičská 845/21 703 00 Ostrava-Vítkovice