JavaScript IF-ELSE Statement

JavaScript IF-ELSE Statement cover image
  1. Home
  2. JavaScript
  3. JavaScript IF-ELSE Statement

Each condition has two paths from which we choose one. For example, “If it’s raining, I’ll stay at home else I’ll go out for a stroll.”

Just like the conditions of everyday life, the conditional if statement in JavaScript has an else clause. It allows us to take the alternate path when the condition in if is false.

if (weather == "raining")
   {
   alert("I'll stay at home");
   }
else
   {
   alert("I'll go out for a stroll");
   }

We can extend our if statement we met in the previous session to construct a better confirm box.

var response = confirm("Have you understood the confirm box?");

if (response == true)
   {
   alert("Okay, let us continue");
   }
else
   {
   alert("Go thru the previous session again");
   }

Click here to see how it works.

Note that the statements in the else block are executed ONLY when the condition in if is false.
The following code checks if a number is even or odd and displays an appropriate alert box.

var n = "23";

if (n%2)
   {
   alert("Number is Odd");
   }
else
   {
   alert("Number is even");
   }

Click here to see how it works.

Conditions in JavaScript can either be true or false. A false condition is one in which the result is zero or null. In the code above, the remainder left after dividing an even number by 2 will be zero (number modulus 2 = 0), hence the condition will evaluate to false. However, if the number is odd, the remainder left after dividing the number by 2 will be 1 and the condition will evaluate to true. Thus, the code block inside else will be executed when the number is even. If this sounds confusing, go through the code and read this section once again.

The NOT operator !

The exclamation mark ! is called the NOT operator. It reverses the return value of a condition.
Thus, !(true) is returned as false and !(false) returns true.

var a = 10;

if (!(a == 10))
   {
   alert("The magic of JavaScript");
   }
else
   {
   alert("The beauty of JavaScript");
   }

In the code above, we assign variable a a value of 10. The if statement checks the value of the variable and displays an alert.
So which alert is displayed?

Since a is 10, the condition (a = 10) returns true. However, the NOT operator reverses this condition to false, hence the alert in the else block is displayed.

JavaScript