You learnt about if..else..if chain and how it is useful in devising an algorithm to find whether a number is positive, negative or zero. Well, let’s add some more complexity to the problem and figure out if the number is single digit positive or more than one digit positive number. Single digit positive means that the number lies between one to nine and more than one digit positive number implies that the number is greater than 10.
Let's use the nested if..else statements for this purpose.
Next, let's look at the comparison between the if..else..if chain and the nested if..else statements.
As you learnt in the last video, a number needs to be checked for being single-digit or more than one digit after it has already been deemed as positive, and you saw the existing conditions cannot check for what is required based on the code that has been taken.
But remember that are numerous possibilities to attack a problem and you can always tweak the existing code and make the if-else chain also work for the given requirement. In such a case, you would have to write the conditions separately like these:
var x = 1; if(x === 0) console.log("Neither positive nor negative"); else if(x < 0) console.log("It is a negative number"); else if(x < 10) { console.log('Positive'); console.log("Single digit postive number"); } else { console.log('Positive'); console.log("Not a single positive number"); }
As you can see above, you are not checking for a condition after checking another condition. Rather, you are using an if..else..if chain.
Thus, you need to be judgemental in such scenarios and see if the requirement can be accommodated in the existing code or you need to change your existing code.