[Solved] What does ending the if statement with a } do in javascript exactly?


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 condition1 is evaluated and checked. If it is true, the flow of control enters scope of first if.
  • Now, condition2 is evaluated and checked and if true, the flow of control enters scope of second if and statement1 is executed.
  • If it is false, then the flow of control does not execute statement1.
  • Since there are no more ifs inside the first if, the statement2 is executed.
  • If the first condition1 itself 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 ifelse 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?