Nested code blocks can be used to create a new scope: variables declared within that block cannot be accessed from the outside, and their lifetime
end at the end of the block. However this only happens when you use ES6 let or const keywords, a class declaration or a
function declaration (in strict mode). Otherwise the nested block is redundant and should be removed.
The presense of redundant blocks (the ones which are not part of control flow and do not create a new scope) is confusing and may point to errors in the code.
{ // Noncompliant: redundant code block
var foo = bar();
}
if (condition) {
doSomething();
{ // Noncompliant: redundant code block
doOtherStuff();
}
}
To fix your code remove redundant blocks.
var foo = bar();
if (condition) {
doSomething();
doOtherStuff();
}
let or const keywords or class declarations are not redundant
as they create a new scope.
{
let x = 1;
}
"use strict";
{
function foo() {}
}
if (condition) {
doSomething();
}