# How can I shorten these if-else statements?

edit retag close merge delete

Sort by » oldest newest most voted

There are a few strategies you could try to shorten if-else statements:

1. Use ternary operators: If the if-else statement is simple enough, you can use a ternary operator to condense it. For example:

Original code:

if (x > 0) {
y = x;
} else {
y = 0;
}


Shortened code:

y = (x > 0) ? x : 0;

1. Combine conditions: Look for conditions that can be combined so that you have fewer if-else statements. For example:

Original code:

if (x > 0 && y > 0) {
z = x + y;
} else {
z = 0;
}


Shortened code:

z = (x > 0 && y > 0) ? x + y : 0;

1. Use switch statements: If you have multiple if-else statements that are checking the same variable, you can use a switch statement to condense the code. For example:

Original code:

if (x == 1) {
y = 10;
} else if (x == 2) {
y = 20;
} else if (x == 3) {
y = 30;
} else {
y = 0;
}


Shortened code:

switch (x) {
case 1:
y = 10;
break;
case 2:
y = 20;
break;
case 3:
y = 30;
break;
default:
y = 0;
break;
}

1. Use functions: If you have a long if-else statement that performs a specific task, consider breaking it out into a separate function. This can make your main code more readable and easier to follow. For example:

Original code:

if (x > 0 && y < 0) {
z = x * y;
} else if (x < 0 && y > 0) {
z = x + y;
} else if (x == 0 || y == 0) {
z = 0;
} else {
z = y / x;
}


Shortened code:

function calculateZ(x, y) {
if (x > 0 && y < 0) {
return x * y;
} else if (x < 0 && y > 0) {
return x + y;
} else if (x == 0 || y == 0) {
return 0;
} else {
return y / x;
}
}

z = calculateZ(x, y);

more