Converting if-else statement to if-else if-else statement

3020 views if-statement
5

How do I convert this nested if-else statement into a non-nested if-else if-else statement? You may need to add some boolean operators to make this completely non-nested:

if (ball > 0) {
    if (cup > 0) {
        console.log(“I have a ball and cup.”);
    } else {
        console.log(“I have a ball.”);
    }
} else {
    if (cup > 0) {
        console.log(“I have a cup”);
    } else {
        console.log(“I have nothing”);
    }
}

answered question

1 Answer

0

If I understand what you are trying to do, then maybe this can help:

if (ball > 0 && cup > 0) {
    console.log(“I have a ball and cup.”);
} else if (ball > 0) {
    console.log(“I have a ball.”);
}
if (ball <= 0 && cup > 0) {
    console.log(“I have a cup”);
} else if (ball <= 0) {
    console.log(“I have nothing”);
}

Instead of nesting if-else statements, you can just check for multiple conditions in each if statement.

posted this

Have an answer?

JD

Please login first before posting an answer.