Here’s an example to understand nested conditions versus composite conditions
Say we code up this statement
Bring an umbrella if it’s raining but wear a raincoat if it’s windy
Here’s one way to interpret the statement and express it in code
let rainy // boolean true if raining false otherwise
let windy // boolean true if windy false otherwise
let umbrella // boolean true if umbrella needed false otherwise
let raincoat // boolean true if raincoat needed false otherwise
// assume rainy and windy have some values
This expression uses composite conditions
// block 1: composite condition
if(rainy && windy) {
umbrella=false
raincoat=true
} else if(rainy && !windy) {
umbrella=true
raincoat=false
} else {
umbrella=false
raincoat=false
}
This formulation uses nested conditions
// block 2: nested condition
if(rainy) {
if(windy) {
umbrella=false
raincoat=true
} else {
umbrella=true
raincoat=false
}
} else {
umbrella=false
raincoat=false
}
Blocks 1 and 2 are equivalent in that for any given values of rainy and windy the combined values of umbrella and raincoat are the same after either block executes
Now what can we say about the following variants?
// block 3: composite without first else of block 1
if(rainy && windy) {
umbrella=false
raincoat=true
} else {
umbrella=false
raincoat=false
}
// block 4: nested condition without inner else of block 2
if(rainy) {
if(windy) {
umbrella=false
raincoat=true
}
} else {
umbrella=false
raincoat=false
}
Blocks 3 and 4 are not equivalent to blocks 1 and 2 in that for some values of rainy and windy the combined values of umbrella and raincoat do not match the combined values of the pair after block 1 or block 2
This is apparent since two boolean variables umbrella and raincoat have four possible combinations of values - blocks 1 & 2 establish 3 distinct combinations of values for the variables but blocks 3 and 4 only establish 2 combinations
None of these blocks is right or wrong - each represents some understanding of the English statement - they are however different understandings resulting in different outcomes