How can you have a global variable defined inside a scope?

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

Link to the challenge:

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.

1 Like

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.

1 Like

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.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.