How to use javascript if else statements?

In this article, lets discuss the usage of the javascript if else statement. Javascript If else statement is a conditional statement which is used to perform different actions based on the different conditions.

In javascript, we have the different conditional statements.

  • IF statement used to execute a set of a statement if a specific condition is true.
  • Else Statement is used to execute a set of a statement if the same IF condition is false.
  • Else IF Statement is used to specify a new condition to test, if the preceding IF condition is false.
  • switch is used to select one of many blocks of code to be executed

Syntax

if (condition1) { // Condition that evaluates to true or false

  /* block of code to be executed if condition1 is true */

} else if (condition2) {

  /* block of code to be executed if the condition1 is false and condition2 is true */

} else {

  /* block of code to be executed if the condition1 is false and condition2 is false */

}

Example

If the current day is 0 or 6, greet the user with message “Yeh, its weekend!” , if the current day is between 1 to 5, greet the user with “Meh, Its a working day!“. Otherwise say, “Not a valid day! Please enter correct input.“.

var currentDay = new Date().getDay(); 

if (currentDay = 0 || currentDay =6) {

  greeting = "Yeh! Its weekend. :) ";

} else if (currentDay > 0 && currentDay <6) {

  greeting = "Meh, Its a working day! :( ";

} else {

  greeting = "Not a valid day! Please enter correct input. ";

}

This is the syntax and usage guide of the javascript if else statement.

See also:

Javascipt try catch statements

Thanks for reading this tutorial. If you have any questions or improvements with respect to this tutorial, Please feel free the comment below or send me an email at [email protected]

Summary
How to use javascript if else statement
Article Name
How to use javascript if else statement
Description
This article explains how to use javascript if else statements which is used to perform different actions based on the different conditions with examples.
Author
Publisher Name
askvikram.com
Publisher Logo

Leave a Comment