ES6 - Compare Scopes of the var and let Keywords

Tell us what’s happening:
Describe your issue in detail here.
I’m stuck guys

  **Your code so far**
function checkScope() {
"use strict";
let i = 'function scope';
if (true) {
  i = 'block scope';
  console.log('Block scope i is: ', i);
console.log('Function scope i is: ', i);
return i;
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge: ES6 - Compare Scopes of the var and let Keywords

Link to the challenge:

This is a confusing exercise, bc you can’t access the outer block i in my opinion. (this comment is just for discussion)

Try this in the browser console:

{ let c = 5 }
{let c = 6}

Then you could use a similar idea in the exercise.

If you have one block inside another, you can just do the same thing: a variable at an inner scope -using let or const - won’t overwrite an outer scope.

It’s confusing, for sure.

I think the reason is that inside the block, you are still not declaring the variable. You need to declare it so JS know that they are two different variables. You can’t add var to the i in the block because it would be in the same scope as the original i. But if you use let for the block i, it will see it as a different scope, the block level scope.

So, you’re halfway there - you’re using let on the function scope, now you need to do it in the block scope. Technically, you only have to do it in the block scope since JS would understand that it is a different scope, but you shouldn’t use var, so we need to change both of them.

Keep in mind, having variables with the same name in different scopes (shadowing) is a bad practice, but it is a good way to talk about scope.

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