JavaScript If Else - Java Script

What is Javascript If-else?

While writing a code, you will come across the scenario when you need to perform one out of a given set of paths. In such cases, you have to use conditional statements that enables your program to takeright decisions and perform right actions.

Conditional statements in JavaScript are often used to carry out different operations based on different conditions.

Flow Chart of if-else

Flow Chart of if-else

The below flow chart illustrates how the if-else statement works.

There are mainly three forms of if..else statements in JavaScript.

  • if statement
  • if...else statement
  • if...else if... statement.

The if statement in JavaScript is a basic control statement that allows you to make decisions and execute the code conditionally.

Syntax

The signature for a fundamental if statement is given below−

Here is how we evaluate a JavaScript expression using conditional if statement. If the resulting value of the expression is true, the block of code given inside the loopis executed. If the resulting value of the expression is false, then no codewill be executed. Many times, comparison operators are used while making decisions.

Example

Try the below example which explains how a conditional if statement works.

how a conditional if statement works

How to use if...else statement?

The 'if...else' statement is another form of conditional statement that offers an alternative way when the condition fails..

Syntax:

Here is how we evaluate a JavaScript expression using conditional ‘if..else’statement. If the resulting value of the expression is true, the n it executes the statements given in ‘if’ block. If the resulting value of the expression is false, then it executes the statements given in else block.

Example

Try the below example which explains how a conditional if…else statement works.

How to use if...else statement

How to use if...else if... statement in Java Script?

The if...else if... statement is extension of if…else that allows JavaScript to takeright decisions out of many conditions.

Syntax:

The signature of an if-else-if statement is given below −

The ‘if..else..if’conditional statement is a chain of if-else-if statements, where every if is a part of the else of the previous statement. If the resulting value of the expression is true then Statement(s) are executed.ifnone of the conditions is true, then the else block is executed.

Example

Try the below example which explains how a conditional if-else-if statement works.

if-else-if statement works


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Java Script Topics