So the code looks like as follows.
if () {
do something;
}
else if () {
do something;
}
.
.
.
else if () {
do something;
}
else {
do something;
}
Does the else at the bottom only act if the else if above it is not satisfied or does it act if the beginning if statement is not satisfied?
2
Answers
It will check the condition of each
if
/else if
sequentially. When checks and sees that the condition is true then it will execute the code inside. If none of the aboveif
/else if
are true then it will execute whatever inside theelse
statement.For more information, see Javascript if else else if.
I made a testing snippet for you to play with. You can choose number between 1 to 5 to see how the
if
/else if
are working. After that, you should try any other input to see how theelse
is working.There are two different kinds of
if..else
constructs. The first is a simpleif-else
:The next is an
if-else-if
:You can also use
else-if
as many times as you like, e.g.:And every part of an
if..else
is optional, except for the initial if block. So if you don’t want to do anything if condition is not true, you can just omit the else block entirely: