I am trying to have this exercise resolved by following the theory of having a global variable defined outside of a scope, however, when I do that, the function is not referring to function i.
The solution for this exercise is confusing me even more, as I see that no variable is even declared outside of the scope. Here is the code I am trying to have working out.
what am I missing ?
**Your code so far**
let i = 'function scope';
function checkScope() {
if (let i = "block scope";) {
console.log('Block scope i is: ', i);
}
console.log('Function scope i is: ', i);
return i;
}
console.log(checkScope());
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:93.0) Gecko/20100101 Firefox/93.0
Challenge: Compare Scopes of the var and let Keywords
I canāt even run that code because you put the declaration into the if-condition.
The āscopeā for āletā is everything inside the {} where itās written within and all āchildrenā (nested {} ). Meaning once you close these brackets, the variable will no longer exist.
So far for the scope.
If you put the declaration into the if-case instead of the condition, you might even get a reasonable result.
Putting a variable declaration inside an if condition doesnāt make any sense, but if we ignore that bitā¦ You have declared two different i variables because you used let both times. Declaring a local variable that happens to have the same name as a global variable is fine. Within the scope of the local variable, that name will refer to the local variable and the global one will be untouched.
Yest youāre right, the declaration should go outside of the if-condition but I am still trying to figure out the solution published on this exercise as it shows an apparent function of global scope inside a block function.
I am still puzzled of why this is not a valid solution to this exercise, considering that the global function is defined outside of the scope
let i = 'function scope';
function checkScope() {
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());
You gave this variable the value āfunction scopeā but it isnāt in the function scope. Itās in the global scope because it is outside the function.
You are right in general - however the test cases donāt include a test for that.
Instead itās failing the āi in the if-statement should be āblock scopeāā test. Even though this isnāt affected.