can you add Nested if
Statements in else
in javascript?
if (condition === true) {
} else {
if(condition === true) {
} else {
}
}
CodePudding user response:
As mentioned in the comments, sure you can, and it even makes sense as long as you are checking for different conditions.
However, this reads much more natural:
if (condition1) {
// Your code running if condition1 === true
} else if (condition2) {
// Some other code running if condition2 === true
} else {
// Code running for all other cases
}
Always avoid nesting if possible.
Also, there is no point in checking if a condition === true, as in itself it represents a boolean value.
There is also something to be said for never using else at all... But you can google and read about that to your own leisure.
CodePudding user response:
Simply use an encapsulation pattern. Extract the logic elsewhere, so your main function remains easy to read.
function checkFooEdgeCase(condition){
return condition === "foo" ? "do foo stuff" : "do other stuff"
function foo(condition) {
if (condition === "true") return "do stuff"
return checkFooEdgeCase(condition)
}
CodePudding user response:
Yes, you can. consider the example below:
let sum = 35;
if (sum % 10 == 0){
console.log("a");
} else if (sum % 2 == 1){
if (sum % 5 == 0 && sum % 2 == 0){
console.log("b");
} else if (sum % 5 == 0){
console.log("c")
} else {
console.log("d")
}
} else {
console.log("e")
}
More examples and explanation here: https://exlskills.com/learn-en/courses/javascript-fundamentals-basics_javascript/conditional-statements-zgrXFcSqdfIF/the-if-statements-YcHrGQKxvTOI/nested-if-statements-nSAoxbDFvMOq