Today I’m refactoring someone’s code from var
to let
which should be used in modern JS and declared variables inside of if statements occur a lot in the code. So this made me wonder is it ok to declare variables inside of if statements or should it be avoided in JS?
var Example1 = "test";
if (Example1 == "test") {
var test1 = true;
}
if (test1) {
console.log("Test 1 works!");
}
// Refactored code do not work with let
let Example2 = true;
if (Example2 == "test") {
let test2 = true;
}
if (test2) {
console.log("Test 2 works!");
}