JavaScript: if...else statements
Conditional Statement
A conditional statement is a set of commands and the commands execute if a specified condition is true. There are two conditional statements in JavaScript : if...else and switch.
JavaScript if...else statement
Executes a group of statements if a logical condition is true. Use the optional else clause to execute another group of statements.
Syntax
For single statement: if (condition) statement_1 [else statement_2]
Example:
In the following example if else statement check whether an input marks is greater than 50 or not.
HTML Code
JS Code
View the example in the browser
JavaScript if...else if statement
For multiple conditions, we can use else if.
Syntax
statement_1
[else if (condition_2)
statement_2]
...
[else if (condition_n_1)
statement_n_1]
[else
statement_n]
Parameters
condition_1, condition_2 : Can be any JavaScript expression that evaluates to true or false. Parentheses are required around the condition. If the condition evaluates to true, the statements in statement_1 are executed, otherwise, statement_2 is executed.
statements_1, statements_2 : Can be any JavaScript statements, including further nested if statements.
It is a good practice to use a block statement ( {....}) to execute multiple statements. See the following syntax :
Syntax
{
statements_1
}
else
if (condition_2)
{
statements_2
}
Example:
Here the if else if.. statement checks the grade of Math. on some conditions.
HTML Code
JS Code
View the example in the browser
Practice the example online
JavaScript nesting if statements
Putting one if statement inside another if statement is called nesting. See the following syntax:
Syntax
{
if (condition)
{
if (condition)
{
statement_1
}
else
{
statement_2
}
}
}
else
{
statement_3
}
Previous: JavaScript: Block statement
Next: JavaScript: Switch statement
Test your Programming skills with w3resource's quiz.