Nuances of variable scope in if-else constructs in JavaScript

The scope of variables has some nuance. Let's look at it with an example. Let's declare the variable res with one value outside our condition, and change this value to another inside the condition:

let res = 1; if (true) { res = 2; } console.log(res); // shows 2

As you can see, the variable res has changed inside the condition. However, everything will change if the variable res is also declared inside the c ondition through let:

let res = 1; if (true) { let res = 2; // declare a variable with let } console.log(res); // shows 1, not 2!

The thing here is that the declaration of a variable through let inside the condition created the local variable res.

That is, there is one variable res inside the condition, and another one outside it. You can verify this by printing the value of the variable to the console inside the condition:

let res = 1; if (true) { let res = 2; console.log(res); // shows 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, prints the value undefined to the console for any age value. Please fix the code author's mistake. Here is the problematic code:

let age = 17; let adult; if (age >= 18) { let adult = true; } else { let adult = false; } console.log(adult);

The author of the code below wanted to perform an age validation for reaching of 18 years. After checking the code, it turned out that if the age is equal to or greater than 18 years, then true is written to the variable adult, as it should be, however, if the age is less than 18, then the variable adult has the value undefined. Please fix the code author's mistake.

Here is the problematic code:

let age = 17; let adult; if (age >= 18) { adult = true; } else { let adult = false; } console.log(adult);

The author of the code below wanted to perform an age checking. The code, however, prints the value undefined to the console for any age value. Please fix the code author's mistake.

Here is the problematic code:

let age = 17; let res; if (age >= 18) { if (age <= 23) { let res = 'from 18 to 23'; } else { let res = 'greater than 23'; } } else { let res = 'less than 18'; } console.log(res);

The author of the code below wanted to perform an age checking. The code, however, when the age value is greater than 18 years, prints the value undefined to the console. Please fix the code author's mistake.

Here is the problematic code:

let age = 19; let res; if (age >= 18) { let res; if (age <= 23) { res = 'from 18 to 23'; } else { res = 'greater than 23'; } } else { res = 'less than 18'; } console.log(res);
enru