Question
Would variables declared in an if
statement be accessible directly outside the if
statement?
Answer
No, variables declared inside an if
statement would not be accessible directly outside an if
statement because if
statements have their own scope. How might you set a value based on a conditional then? You can either use a ternary operator or declare the variable outside the if
/else
statement and define the variables value inside the if
/else
.
This does not work:
let capacity = 50;
let numberOfPeople = 80;
if(numberOfPeople > capacity) {
let numberOfExtraPeople = numberOfPeople - capacity;
}
else {
let numberOfExtraPeople = 0;
}
// Prints undefined because numberOfExtraPeople is not in this scope
console.log(numberOfExtraPeople);
However, this works:
let capacity = 50;
let numberOfPeople = 80;
let numberOfExtraPeople;
if(numberOfPeople > capacity) {
numberOfExtraPeople = numberOfPeople - capacity;
}
else {
numberOfExtraPeople = 0;
}
// Prints 30 because numberOfExtraPeople was declared in the same scope as the console.log
console.log(numberOfExtraPeople);