728x90
SMALL
#javascript
#javascript conditionals if, else if, else
We use if, else if, else when we want to do something when a certain condition is met.
grammar
if ( condition1 ) {
statement1
}
Executes statement1 if condition1 is met.
if ( condition1 ) {
statement1
} else {
statement2
}
Executes statement1 if condition1 is met, otherwise executes statement2.
if ( condition1 ) {
statement1
} else if ( condition2 ) {
statement2
}
Executes statement1 if condition1 is met, and executes statement2 if condition2 is met.
if ( condition1 ) {
statement1
} else if ( condition2 ) {
statement2
} else {
statement3
}
Executes statement1 if condition1 is met, statement2 if condition2 is met, and statement3 if both are not met.
example
Here's an example that when you enter a number, it shows whether it's less than 10 or 10 or greater than 10.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript | if</title>
</head>
<body>
<script>
var jbNum = prompt( 'Enter Number', '' );
if ( jbNum < 10 ) {
document.write ( '<p>Your number is less than 10.</p>' );
} else if ( jbNum == 10 ) {
document.write ( '<p>Your number is 10.</p>' );
} else {
document.write ( '<p>Your number is greater than 10.</p>' );
}
</script>
</body>
</html>
For example, entering 20 would result in:
728x90
LIST
'Javascript' 카테고리의 다른 글
[JavaScript] JavaScript / Repeat Statements / while, do - while, for (0) | 2022.08.01 |
---|---|
[JavaScript] JavaScript/conditional statement/switch (0) | 2022.08.01 |
[JavaScript] JavaScript/operator/typeof operator (0) | 2022.08.01 |
[Javascript] JavaScript / operator / comparison operator (0) | 2022.07.29 |
[Javascript] JavaScript / data type / string (0) | 2022.07.29 |