Java Script


JavaScript Tutorial


Admission Enquiry Form


What is If Else Statement in JavaScript?

If statement is conditional statement in JavaScript.It executes the 'if block' only when expression is true.But, if condition is false it will execute else block.

Syntax of If Else Statement...

if(condition)
  {
  //number of statements
  }
else
  {
 //number of statements 
  }

Example of if else statement to check number is even or odd:

<html>
<head>
<title>if else statement</title>
</head>
<body>
<script>
var num=4;
if(num%2==0)
{
document.write("Number is even");
}
else
{
document.write("Number is odd");
}
</script>
</body>
</html>

Output

Number is even

In the above example, the value of num is 4. When control check the if statement it will be true because 4 is divisible by 2 and give the remainder 0.So, you will see the above output.


Example of if Else Statement to check whether number is positive or negative:

<html>
<head>
<title>if else statement</title>
</head>
<body>
<script>
var num;
num=prompt("Enter a number ");
if(num>0)
{
document.write("number is positive");
}
else
{
document.write("number is negative");
}
</script>
</body>
</html>

Output

Enter a number -4
number is negative


In the above example,we are using the prompt function for taking the input from the user.Initially if the user enters any positive number then the control will come inside the If block because the positive number is greater than 0 and execute if block.But, if user will enter any negative number like -4 then control will go to else block and give the above output.