Use of if statements in javascript

  • 2020-03-29 23:53:13
  • OfStack

Some select statements in javascript:
1. If statement when a condition is specified to be true, the code for that condition is executed.
2, the if... The else... Statement executes this code when the statement specifies that the condition is true, and other code if the condition is false.
3, if... Else if... The else... Statement this statement selects multiple pieces of code to execute together.
4. Switch statement selects multiple codes to be executed together.

If statement
If (condition) {
The code that executes when the condition is true;
}

Ex. :
 
<script> 
function myFunction() 
{ 
var x=""; 
var time=new Date().getHours(); 
if (time<20) 
{ 
x="Good day"; 
} 
document.getElementById("demo").innerHTML=x; 
} 
</script> 

The if... The else... statements
If (condition) {
When the condition is true, the code is executed
} else {
The code executed when the condition is not true (the condition is false);
}
Ex. :
 
<script> 
function myFunction() 
{ 
var x=""; 
var time=new Date().getHours(); 
if (time<20) 
{ 
x="Good day"; 
} 
else 
{ 
x="Good evening"; 
} 
document.getElementById("demo").innerHTML=x; 
} 
</script> 

The if... Else if... The else... statements
If conditions (1) {
When condition 1 is true, execute the code;
}else if(condition 2){
When condition 2 is true, execute the code;
} else {
Code executed when conditions 1 and 2 are not true;
}
Ex. :
 
<script> 
function myFunction() 
{ 
var x=""; 
var time=new Date().getHours(); 
if (time<10) 
{ 
x="Good morning"; 
} 
else if (time<20) 
{ 
x="Good day"; 
} 
else 
{ 
x="Good evening"; 
} 
document.getElementById("demo").innerHTML=x; 
} 
</script> 

Related articles: