else-if condition in if-else statements: While specifying conditions for if-else statements, there may arise a need to include more than just two scenarios. For example, suppose we have a variable ‘n’ and we have to check if it is positive or negative. JS code for this problem would look like this: Quite simple, right? However, suppose we twist this problem a bit. If we have to check if the value of ‘n’ is positive, negative, OR zero. Can we do it using only if-else? No, right? Here comes the scenario where we have to check more than two conditions and give output for each. This is where else-if comes into the game. Structure of if else-if else looks something like this: If (condition 1) { statements } else if (condition 2) { statements } else { statements } Working for the above code is explained as follows: Condition 1 is checked first. If it is true, statements inside the first block are executed and the remaining conditions are not checked. If t...
Comments
Post a Comment