A Platform To Learn To Code

JAVASCRIPT IF STATEMENT



Conditional Statements : Conditional statements are those statements in which there is some decision to be taken and then perform further tasks. While writing code we often face a similar situation where we take a decision for a block of code to be executed when certain conditions satisfy.

Decisions making while coding is very frequent. In javascript we have following decision making ways :

  1. if statement
  2. if-else statement
  3. else if statement
  4. switch statement


1. if statement

if statement is the most basic statement of conditional statement. if statement executes a block of code when the condition is true, if condition is false then codes after if statement executes.

Here is a flow diagram that shows how if statements executes.

if condition flow diagram

Syntax:

if (condition) {
    // execute this block if the condition is true...
}

Example

Run the code

In the above example condition x==10 is true so it executes the statement inside if block.


2. else statement

In a condition when we want to execute some code when the condition gets false, we use else statements. It represents a block of code to be executed in case condition of if statement becomes false.

else statement can't be used alone it must be used after the if statement.

Syntax :

if (condition) {
    // execute this block if the condition is true...
}
else {
    // execute this block if the condition is false...
}
if else condition flow diagram

Example

Run the code

3. else if statement

else if statement is used when we want to check another condition if the first condition is false.

else if statement is used after any if statement.

Syntax :

if (condition) {
    // execute this block if the condition is true...
}
else if (condition) {
    // execute this block if the condition is true...
}
else if (condition) {
    // execute this block if the condition is true...
}
else if condition flow diagram

Example

Run the code

4. switch statement

switch statement is a collection of many conditions in a more ordered manner which work exactly as if statement. We will study switch statements in the next chapter in detail.