What is JavaScript Conditional Statements?
Conditional statements perform actions based on a condition. For example we can say that if it is raining don’t go out otherwise go out.
Syntax of JavaScript if statements:
if(condition)
{
any action
}
Syntax of JavaScript if and else statements:
if(condition)
{
any action
}
else
{
any action
}
- for conditional statements the keywords are if, else, else if.
- if is followed by a condition usually enclosed in parenthesis.
- curly braces { } are used for defining an action that will be executed.
- if the first condition is not met then the the action defined under else block will be executed.
Example of JavaScript if and else statements:
1 2 3 4 5 6 7 8 9 10 11 12 |
<script type="text/javascript"> var MyWebsiteName = "www.Cramerz.com"; if (MyWebsiteName == "cramerz.com") { document.write("My website name is cramerz.com") } else { document.write("My website name is www.Cramerz.com") } </script> |
In above example we have created a variable MyWebsiteName with a value www.cramerz.com. We are then checking if the value of the variable is cramerz.com or www.cramerz.com
Another Example of JavaScript if and else statements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<script type="text/javascript"> var date = new Date() document.write(date) document.write("<BR>") var time = date.getHours() document.write(time) document.write("<BR>") if ( time == 15) { document.write("It's 3PM right now") } else { document.write("Do you know what's the time?") } </script> |
In above example we created a variable date and then assigned it today’s date by using Date() JavaScript method. Date () is a built in JavaScript method that will automatically give us today’s date.
Then we have created another variable called time and get the time out of our previous date method by using getHours() method.
At the end we are using a JavaScript if condition to check if it is 3 pm right now. If it is not 3 pm then we are asking user about the current time.
Syntax of JavaScript if with many conditions
We can check for more than one condition in our if statements.
if ( condition && condition || condition )
{any action}
else if ( condition ){any action}else if ( condition ){any action}
else {any action}