JavaScript if else statement

Programming language can contain the code of one line or many lines. To control the execution of all these code lines, use the if statement if the statement is of 3 types -

1 if statement

2 if else statement

3 if else if statement

1. if statement

If a condition is given in the if statement, the code is run if the condition is true and if the content given in is displayed in the web page, if the condition is false then the code is not run and the output in the web page is not displayed anything.

Syntax

if(expression){

//content

}

Example 1

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

<script>

var a = 2;

if(a>1){

document.write("value of a is greater than 1"); }

</script>

</body>

</html>

Output

value of a is greater than 1

2 if else statement

If a condition is given in the if statement, the code is run if the condition is true and if the content given in it is displayed in the web page, if the condition is false then the content in the else is displayed in the web page.

Syntax

if(expression){

//content display if condition is true

}

else{

//content display if condition is false

}

Example 2

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

<script>

var a = 2;

if(a<1){

document.write("a is less than 1");

}

else{

document.write("a is grater than 1");

}

</script>

</body>

</html>

Output

a is grater than 1

3 if else if statement

If a condition is given in the if statement, if the condition is true then the statement given in if is displayed in the web page, if the condition is not true then interpreter checks all else if statement if it also has no condition true then in else The given code is run.

In this, you can use two or more else if statements.

Syntax

if(expression1){

//content display if expression1 is true

}

else if(expression2){

//content display if expression2 is true

}

else if(expression3){

//content display if expression3 is true

}

else{

//content display if expression is false

}

Example 3

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

<script>

var a = 4;

if(a==1){

document.write("a is equal to 1");

}

else if(a==2){

document.write("a is equal to 2");

}

else if(a==3){

document.write("a is equal to 3");

}

else{

document.write("a is not equal to 1, 2 or 3");

}

</script>

</body>

</html>

Output

a is not equal to 1, 2 or 3


Connect with us

facebook logo
Email : contact@amcodestar.com
© Copyright amcodestar.com 2020 - 2023 All Rights Reserved.
About us     term and condition      comment policy
DMCA.com Protection Status