JavaScript if () { ... } else { ... }
is used to make conditional judgments. For example, depending on the age of different content, you can use the if
statement to implement the following:
var age =; if // if age >= 18 is true, the IF statement block is executed Alert (' adult 'else// Otherwise execute the ELSE statement block alert (' Teenager ');}
Where else
the statement is optional. If the statement block contains only one statement, you can omit {}
:
var age =; if (age >=) alert (' adult '); Else alert (' teenager ');
{}
the danger of omitting is that if you later want to add some statements and forget to write {}
, you change if...else...
the semantics, for example:
var age =; if (age >=) alert (' adult '); Else console.log (// Add a line of logs // <-This line of statements is no longer in the else's control.
The clause in the above code is else
actually only responsible for execution console.log(‘age < 18‘);
, the original alert(‘teenager‘);
control is not in the if...else...
scope, it will execute each time.
That's why we suggest to always write {}
.
Multi-line condition judgment
If you want to judge the condition more carefully, you can use multiple if...else...
combinations:
var age = 3; if (age >=) { alert (' adult 'elseif (>= 6) { alert (' Teenager 'else { alert (' Kid ');}
These multiple if...else...
combinations are actually equivalent to two layers if...else...
:
var age = 3; if (age >=) { alert (' adult 'else { if (>= 6) { alert (' teenager '); Else { alert (' Kid ');} }
But we usually put else if
ligatures together to increase readability. The else
slight drop here {}
is no problem, because it contains only a single if
statement. Note that the last individual does not have to be else
omitted {}
.
Note that if...else...
the execution of the statement is characterized by a two selection, in multiple if...else...
statements, if a condition is established, then the subsequent will not continue to judge.
if
What if the conditional judgment statement result is not true
or false
what? For example:
var s = ' 123 '; if // conditional calculation result is 3 //}
JavaScript treats,, null
undefined
0
, NaN
and empty strings ‘‘
as false
other values are treated as such, true
so the result of the above code condition judgment is true
.
JavaScript Basics (7) Conditional judgment