Javascript Conditional stat

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:

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:

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}