Why do we Use if/else Statements in Javascript

Why do we Use if/else Statements in Javascript

In this article, we will see why do we use if/else statements in javascript.

Why use if and else statement

if/else statement is used to execute a block of code based on a condition. For example, When we play video games, if we click quit, it will ask the question “do you really want to quit this game” then if we say “yes” it will close, and if we say no the game will continue. Based on the condition of yes or no, the program decides whether to continue the game or not. “if/else” statement is used to handle such a situation.

Example code

var person1=30;
   var person2=4;
   if(person1 > person2){
      document.write("Person 1 is older")
   }
   else{
      document.write("Person 2 is older")
   }

Output:

why do we use if/else statements in javascript

Steps:

In the above code, we have got the age of two persons and find out which one is older using the if/else statement.

Leave a Reply