Conditional Statements
Usually when writing code, you always need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this task.
In JavaScript, we can use the following conditional statements:
if statement - Use this statement to execute code only when the specified condition is true
if... else statement - execute code when the condition is true and other code when the condition is false
if...else if....else statement - use this statement to select one of multiple blocks of code to Execute
switch statement - Use this statement to select one of multiple blocks of code to execute the
if statement
Syntax:
if (expr){
statement
}
This syntax indicates that if expr If the expression is true, the code within {statement} is executed.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var x = 3; var y = 1; if (x>y) alert("x 大于 y"); </script> </head> <body> </body> </html>
if…else
Syntax:
if ( expr){
statement1
} else {
statement2
}
This syntax means that as long as expr is established, statement1 will be executed, otherwise statement2 will be executed.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var x = 1; var y = 3; if (x>y){ alert("x大于y"); } else { alert("x小于等于y"); } </script> </head> <body> </body> </html>
##if...else if...else
Grammar:if (expr1){ statement1
} else if (expr2) {
statement2
} else {
statement3
}
##This syntax means that as long as expr1 is true, execute statement1, otherwise detect expr2; if expr2 is true, execute statement2; if expr2 is also true, execute statement3.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var x = 3; var y = 3; if (x>y) { alert("x大于y"); } else if (x<y) { alert("x小于y"); } else { alert("x等于y"); } </script> </head> <body> </body> </html>