V7022. It is possible that this 'else' branch should belong to the previous 'if' statement.
The analyzer has detected a potential error: the formatting of the else statement does not align with the program execution logic.
Look at the example:
function checkValue(x, y) {
if (x === 10)
if (y === 20)
console.log("x is 10 and y is 20");
else // <=
console.log("x is not 10");
}
Such else is called dangling else, and which if statement it refers to depends on the programming language. The formatting here suggests that else refers to the first if, but in JavaScript, it always refers to the most recent if. In other words, the statement above will be similar to the following:
function checkValue(x, y) {
if (x === 10) {
if (y === 20) {
console.log("x is 10 and y is 20");
} else {
console.log("x is not 10");
}
}
}
To avoid any confusion, we suggest following the advice in the Google JavaScript Style Guide. It recommends using braces for all control statements, even those with a single operation in their body.
The fixed code:
function checkValue(x, y) {
if (x === 10) {
if (y === 20) {
console.log("x is 10 and y is 20");
}
} else {
console.log("x is not 10");
}
}