The if...else statement is to execute the code when the specified condition is true
, and execute the code after else
when the condition is false
.
Javascript if else Syntax :
if(condition)
{
code to execute when the condition is true
}
else
{
code to execute when the condition is false
}
Suppose we want to check a user's age, if the age is greater than or equal to 18 years old, the user is an adult, otherwise the user is not an adult. The code representation is as follows :
<script type="text/javascript">
var myage = 18;
if(myage>=18) // myage>=18 is the judgment condition
{ document.write("You are an adult."); }
else //Otherwise the age is less than 18
{ document.write("Under 18 years old, you Not an adult." ); }
</script>
Task - Exercise 8
Assuming that Samuel Ben scored 80 points in an English test, use the if...else
statement to check whether the test score is passed (60 points or more is a pass). Supply the codes on lines 8 and 12 to complete the function.
Task Code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Judgement statement</title>
<script type="text/javascript">
var score =80; //score variable stores grades, the initial value is 80
{
document.write("Great, passed the grade.");
}
{
document.write("Come on, I failed the grade.");
}
</script>
</head>
<body>
</body>
</html>
//= htmlentities($post["body"]); ?>