JavaScript If else statement
There are times you write a program, you face a lot of challenges such as fulfilling a task only if a condition is met. In such situation, you need to make a decision. Decision making in programming is similar to programming. There are cases when you need to do something but a condition must be met before the task is done. There are times you want some action to be performed by the user ONLY when they have met a particular condition.
This leads us to making decisions when writing code.
In this tutorial, we would learn to write code that meet the condition based on the situation.
There are 3 forms of if statement in JavaScript.
• If statement
• If...else statement
• If else...if statement
If statement
The if statement is a control statement that allows decision making and execution of statement based on the condition stated.
Let's take an example
<html>
<head>
<title>If statement</title>
</head>
<body>
<script>
var x = prompt ("Enter value");
if (x> 5){
document.write("The number is greater than five");
}
</script>
</body>
</html>
Screenshot
Output
• The first will prompt the user to enter value
• The second gives the result
If else statement
The if else statement is a control statement that allows decision making and execution of code based on the condition. Well you might be thinking - is it the same as if statement, well no. It's quite different. The difference is that - when a statement does not meet the condition, the result will be the statement in the else part.
Let's take an example
<html>
<head>
<title>If else statement</title>
</head>
<body>
<script>
var x = prompt ("Enter value");
if (x> 5){
document.write("The number is greater than five");
}
else {
document.write("The number is less than five");
}
</script>
</body>
</html>
Screenshot
If else if statement
This statement allows you to make decision when you have several conditions.
SYNTAX
Example
<html>
<head>
<title>If else if statement</title>
</head>
<body>
<script>
var x = prompt ("Enter value");
var y = prompt ("Enter value")
if (x== y){
document.write(x + "is equal to" + y);
}
else if(x > y){
document.write(x + " is greater than " + y);
}
</script>
</body>
</html>
Screenshot
Please share
JavaScript Syntax
Where do you place JavaScript in HTML document
JavaScript Variables
JavaScript Strings: How to create and manipulate
JavaScript Function: How to define and call a function
How to generate output in JS
JavaScript Switch case
Comments
Post a Comment