ES6: Compare Scopes of the var and let Keywords

Here’s the code I have written

function checkScope() {
"use strict";
  let i = "function scope";
  if (true) {
    i = "block scope";
    console.log("Block scope i is: ", i);
  } else {
  console.log("Function scope i is: ", i);
  return i;
  }
}

But it’s not working.

NOTE: This challenge is in beta.

1 Like

The challenge instructions say “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.” You initialized i to be “function scope” and then inside the if statement block of code, you are reassigning this same i variable to “block scope”. You want the variable i within the if block to be different i.

2 Likes

They are telling you to 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. It means you have to create two variables named i. So, you can write: let i = "function scope"; for one variable and for another one go with let i = "block scope";

3 Likes

You need to use let for both i variables:

function checkScope() {
"use strict";
  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;
}
6 Likes

I tricked the test by putting changing if(true) into if(!true) and funny that it works. But obviously your method is better.

function checkScope() {
"use strict";
  let i = "function scope";
  if (!true) {
    i = "block scope";
    console.log("Block scope i is: ", i);
  } else {
  console.log("Function scope i is: ", i);
  return i;
  }
}
2 Likes

Thanks so much. I have spent some time on this.

thank you so much, very simple but effective answer.

Thanks for all comment