JavaScript if
statements allow code to make decisions. A typical if
statement has the following structure:
if(variable == "value")
{
// Code to execute when condition is true
}
An if
statement causes the block of code between the open {
and close }
to only be executed if the condition between the open (
and close )
is true. When writing a condition, the following operators can be used:
Operator | Description |
---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
JavaScript if
statements are commonly used when validating a form. Create a new HTML
document and add the following code:
<!doctype html>
<html>
<head>
<title>JavaScript If Statements</title>
</head>
<body>
<h1>JavaScript If Statements</h1>
<p>Enter some text:</p>
<input type="text" id="text">
<br>
<button id="check">Check</button>
</body>
</html>
When the button is pressed, we will display a message indicating if the textbox has a value or is blank. We will achieve this by using an if
statement followed by an else
statement. The block of code associated to the else
is executed if the condition of the if
statement is false:
if(variable == "value")
{
// Code to execute when condition is true
}
else
{
// Code to execute when condition is false
}
Add a script
tag below the button in the new doucument. Add the following JavaScript to check the textbox and display a message:
var button = document.getElementById("check");
button.addEventListener("click", function(){
var textbox = document.getElementById("text");
if(textbox.value == "")
{
alert("The textbox is empty!");
}
else
{
alert("The textbox has a value");
}
});
Create a new HTML document, add the standard HTML tags, and a title:
<!doctype html>
<html>
<head>
<title>JavaScript Greeting</title>
</head>
<body>
<h1>JavaScript Greeting</h1>
</body>
</html>
After the title add a script
tag and the following JavaScript:
var now = new Date();
var day = now.getDay();
var hour = now.getHours();
document.write("<p>The current day is " + day + ".</p>");
document.write("<p>The current hour is " + hour + ".</p>");
This code creates a date object and uses the getDay()
and getHours()
to extract the day of the week (0 for Sunday and 6 for Saturday) and the hour of the day (in a 24 hours format).
After the previous JavaScript add an if
statement to display a greeting based on the time of day and day of week:
Condition | Message |
---|---|
Monday | Does someone have a case of the Mondays! |
Friday afternoon | TGIF! |
Weekend | Have a great weekend! |
Other mornings | Good morning! |
Other afternoons | Good afternoon! |
Full tutorial URL:
https://codeadam.ca/learning/javascript-if-statements.html