Conditional Statements

Javascript Conditional Statements

All programming languages provide flow control statements that allows you to control the order in which the code is executed. These control statements enable your program to follow a certain course of action depending on whether a particular condition is met. These conditions are always comparing between variables and data. Some sample conditions are follows:

  1. Is X is bigger than Y ?
  2. Is Y is smaller than X ?
  3. Is X is equal to Y ?
  4. Is X is not equal to Y ?

If you notice the above statements you can see a similarities in the answer of the above conditions. Right....the answer should be YES or NO.

If statement

Conditions in programming languages provide a simple but powerful way to control the flow of execution through a piece of programming code. The if statements in Javascript allow your code to be executed when the condition specified is met.

Syntax

The condition in the if statement is true then the code in the statementBlock will be executed.

example

The above example evaluate 10 is greater than 5 or not. If the condition is true then the code block will execute. Here the condition is true, so the code block will execute your code inside the curly braces.

if...else statement

If you face two possible situations and you want to respond differently for each, then you can use an if...else statement.

Syntax

In the above syntax, program check first statement expression is true, if it is true then first statement block will execute otherwise second statement block will execute

example

if...else if...else

Javascript if else if statement

If you face more than two possible situations and you want to respond differently for each, then you can use an if...else if...else statement.

Syntax

example

Alternative if..else Syntax (? Ternary Operator)

Instead of using if..else statement, you can use shorthand conditional expressions.

Syntax

example

A normal if...else syntax example.

Using Ternary Operator(?)

Switch Statements

Javascript Switch Statements

In the previous section we saw the if...else if statements could be used for checking multiple conditions, if the first condition is not valid, then next is checked, and another, and so on. Likewise a switch statement in Javascript allows you to deal with several possible results of a condition. When you want to check a particular condition for a large number of possible values, switch statement is a more efficient alternative of if...else if statement

Syntax

example