JavaScript If ... Else Getting Started instance tutorial
Conditional declarations in JavaScript are used to perform different actions according to different conditions.
Conditional statement
Often when you write code, you want to perform different actions for different decisions. You can do this by using the code in the conditional statement.
In JavaScript, we have the following conditional statement:
If the declaration-use this declaration if you want to execute some code only if the specified condition is true
If ... else statement-Use this declaration if you want to execute some code if the condition is true if the condition of another code is false
If someone else ... If .... else statement-Use this declaration if you want to select a lot of blocks of code will be executed
Switch statement-Use this declaration if you want to select a lot of blocks code will be executed
If you declare
You should use the IF statement if you want to execute some code only if the specified condition is true.
Grammar
if (condition)
{
Code to was executed if condition is true
}
Please note that if you are writing letters. Using uppercase letters (IF) will result in a JavaScript error! Example 1<script type= "Text/javascript" >
Write a "Good morning" greeting if
The time is less than 10var d=new Date ();
var time=d.gethours ();
if (time<10)
{
document.write ("<b>good morning</b>");
}
</script>if ... else statement if you want to execute some code if one condition is true if the condition of another code is incorrect, if you use .... else statement. Syntax if (condition)
{
Code to was executed if condition is true
}
Else
{
code to be executed if Condit Ion is not true
} instance. Script Type= "Text/javascript"
//if the time is less than,
//you'll get a "good mo Rning "greeting.
//otherwise you'll get a ' good day ' greeting.var d = new Date ();
var time = d.gethours ();
If (Time <)
{
document.write ("Good morning!");
}
Else
{
document.write ("Good day!");
}
</script>if...else If...else statement You should use if .... If someone else ... else statement if you want to select a multiple line execution. Syntax if (condition1)
{
Code to was executed if Condition1 is true
}
Else if (condition2)
{
Code to being Executed if Condition2 is true
}
Else
{
code to being executed if Condition1 and
Condition2 are not true< br>}<script type= "Text/javascript"
var d = new Date ()
var time = d.gethours ()
if (time<10)
{
document.write ("<b>good morning</b>");
}
Else if (time>10 && time<16)
{
document.write ("<b>good day</b>");
}
Else
{
document.write ("<b>hello world!</b>");
}
</script>