SoFunction
Updated on 2025-03-03

Introduction to the use of if statements in javascript

Some selection statements in javascript:
1. If statement When the specified condition is true, the code for the condition is executed.
2. If...else... statement When the statement specifies that the condition is true, the code is executed, and if the condition is executed, other code is executed.
3. If...else if...else... statement This statement selects multiple codes to execute together.
4. Switch statement Select multiple codes to execute together.

if statement
if(condition){
Code executed when the condition is true;
}

example:
Copy the codeThe code is as follows:

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

if...else... statement
if(condition){
When the condition is true, execute the code
}else{
When the condition is not true (the condition is false), the code executed;
}
example:
Copy the codeThe code is as follows:

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

if...else if...else... statement
if(condition 1){
When condition 1 is true, execute the code;
}else if(condition 2){
When condition 2 is true, execute the code;
}else{
When neither condition 1 nor 2 is true, the code executed;
}
example:
Copy the codeThe code is as follows:

<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";
}
("demo").innerHTML=x;
}
</script>