JavaScript IF Statement

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

The beauty of programs lies in the fact that they are able to take decisions on the basis of information you provide. In all the programming languages I’ve come across, the If statement is extensively used for this purpose.
It’s actually quite simple to use the if statement and here is the format of an if statement.

if (condition)
   statements to execute

When JavaScript encounters an if statement, it checks the condition. If and only if, it is found to be true, the statements enclosed within the curly braces are executed. Note, the condition is always enclosed by a pair of parenthesis.

Let’s look at some examples.

var a = 5;
var b = 5;
if (a == b)
   alert("The two quantities are equal");

First, two variables are initialized and assigned the same numeric value (5). The if statement then checks for their equality and pops-up an alert box if the two variables are equal.
The == comparison operator does the job of checking the two variables. The other Comparison operators are:

The == is a ‘Comparison Operator’ while = is an ‘Assignment Operator’. Be sure to use the comparison operator in a condition. If you use the assignment operator, the code will not function and JavaScript will NOT throw an error… it’ll simply reassign the variable on the left.

The ‘Confirm’ Box

A ‘Confirm’ box was displayed when you first entered this page. It’s brought about by using the confirm() method of the window object, similar to the alert box.

confirm("Did you like the movie 'Godfather'?");

Click here to test a confirm box

The confirm box has two buttons, an “OK” and a “Cancel” button. When the user clicks on “OK” the value ‘true’ is returned, while clicking on “Cancel” returns ‘false’. We can capture this returned value in a variable and test it through an if statement. Let’s look at a similar real world example:

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

if (response == false)
   alert("Go thru the sessions again");

Click here to test the code
If you click on the “Cancel” button, confirm returns false as value that is stored in the variable response. The if condition then tests this variable. Since the condition is true (response is equal to false), the statements inside if are executed and you get an alert box.