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.

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;
}
5 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