Introduction:
In this article I am going to explain about the if-else statement in JavaScript and how we can use it.
When writing any program there are may arise situations when we have to take decisions at many places. We have to choose one path out of two so, like other languages JavaScript provides us conditional statement i.e. if-else statement so that we can take decision in programming with JavaScript.
JavaScript supports three types of if-else-statements:
1. If-statement.
2. If-else statement.
3. If..else if...statement.
If statement:
If statement is the fundamental control statement it allows JavaScript to make decisions and execute statements only when certain condition exists.
Syntax:
if(condition) {
// code to be executed if condition is true
}
Example of If-else statement:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>If-else statement example</title>
<script type="text/javascript">
var age = 19;
if (age >= 18) {
document.write("Your are able to vote, Your age is :" + age);
}
</script>
</head>
<body>
</body>
</html>
If-else statement:
We will use if else statement to execute some code if certain condition is true and execute the other portion if condition is false. Here in either of the cases one block will execute.
Syntax:
if(condition) {
// code to be executed if condition is true.
}
else
{
//code that will be executed if condition is not true.
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>If-else statement example</title>
<script type="text/javascript">
var age = 17;
if (age >= 18) {
document.write("Your are able to vote, Your age is :" + age);
}
else {
document.write("Your are not able to vote, Your age is :" + age);
}
</script>
</head>
<body>
</body>
</html>
If-else-if statement:
This is one step more advanced form of conditional statement that allows JavaScript to make a correct decision out of several choices.
Example of if-else-if statement
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>If-else-if statement statement example</title>
<script type="text/javascript">
var percentage = 60;
if (percentage >= 75) {
document.write("Your are passed with honours :" + percentage);
}
else if (percentage >= 60) {
document.write("Your are passed with first division :" + percentage);
}
else if (percentage < 60 && percentage >= 35) {
document.write("Your are passed with second division :" + percentage);
}
else {
document.write("Fail :" + percentage);
}
</script>
</head>
<body>
</body>
</html>
Conclusions:
Through this article we came to know about the if-else statement and how we can use it in Java Script to perform condition checking.
Leave Comment