Let, for simplicity, we have an always satisfied condition:
if (true) {
}
Let's consider the following code:
if (true) {
let res = '!';
}
console.log(res);
As you can see, the value '!'
should
be written to the variable res
. However,
if you run this code, then an error will
be displayed in the console!
The point is that variables declared inside curly braces are only visible inside those braces, and not visible outside. In a scientific way, here we are talking about variable scope.
We can say that the scope of variables declared inside curly braces is only those curly braces. However, if a variable is declared outside the curly braces, then it is visible both inside and outside of them:
let res; // the variable declared outside
if (true) {
res = '!';
}
console.log(res); // shows '!'
In the following example, the variable res
is assigned either the value 1
or the
value 2
depending on the condition:
let num = 5;
if (num >= 0) {
let res = 1;
} else {
let res = 2;
}
console.log(res);
However, if you run this code, an error will be displayed in the console. As you now understand, it's all about the visibility of variables. To solve the issue, declare a variable outside the condition:
let test = true;
let res; // declare the variable outside the condition
if (test) {
res = 1;
} else {
res = 2;
}
console.log(res); // shows 1
The author of the code below wanted to
perform an age validation for reaching
of 18
years. The code, however,
doesn't work. Please fix the code author's
mistake. Here is the problematic code:
let age = 17;
if (age >= 18) {
let adult = true;
} else {
let adult = false;
}
console.log(adult);