The first one is a nested if i.e.
if(condition1) {
if(condition2) {
statement1 ;
}
statement2 ;
}
This will execute statemen1t only when both condition1 and condition2 are true and statement2 whenever condition1 is true. The execution is as follows:
- First
condition1is evaluated and checked. If it is true, the flow of control enters scope of firstif. - Now,
condition2is evaluated and checked and if true, the flow of control enters scope of secondifandstatement1is executed. - If it is false, then the flow of control does not execute
statement1. - Since there are no more
ifs inside the firstif, thestatement2is executed. - If the first
condition1itself is false, then nothing is executed.
The second one is two ifs, not related to one another i.e.
if(condition1) {
statement1 ;
}
if(condition2) {
statement2 ;
}
Here if condition1 is true, statement1 is executed and if condition2 is true then statement2 is executed. The two ifs are not related in anyway. For that use an if–else ladder i.e.
if(condition1) {
statement1 ;
}
else
if(condition2) {
statement2 ;
}
In this case, condition2 will be checked only if condition1 is false.
solved What does ending the if statement with a } do in javascript exactly?