- Let's give you an example:
function checkScope() {
var i = 'function scope';
if (true) {
i = 'block scope';
console.log('Block scope i is: ', i);
}
console.log('Function scope i is: ', i);
return i;
}
console.log(checkScope()); will display
Block scope i is: block scope
Function scope i is: block scope
block scope
- Let's Fix the code so that i declared in the if statement is a separate variable than i declared in the first line of the function. Just be certain not to use the var keyword anywhere in your code.
function checkScope() {
let i = 'function scope';
if (true) {
let i = 'block scope';
console.log('Block scope i is: ', i);
}
console.log('Function scope i is: ', i);
return i;
}
console.log(checkScope()); will display
Block scope i is: block scope
Function scope i is: function scope
function scope
This challenge is designed to show the difference between how var and let keywords assign scope to the declared variable. When programming a function similar to the one used in this exercise, it is often better to use different variable names to avoid confusion.
Top comments (1)
Short, sweet, and to the point. Thanks for sharing!