Compare Scopes of the var and let Keywords- Don't Get It

I can complete the challenge easily. I just don’t understand the concept behind switching var to let.

Please explain as simple as possible on why it’s relevant for this problem. I particularly don’t understand what is meant by:
“This behavior will cause problems if you were to create a function and store it for later use inside a for loop that uses the i variable. This is because the stored function will always refer to the value of the updated global i variable.”

Maybe you can say in a much simpler way.
Tell us what’s happening:

Your code so far


function checkScope() {
"use strict";
  var 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/70.0.3538.77 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords

Nevermind i understand!

Hi richard93x.

FCC say 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";

#Function scope

When you declare a variable in a function, you can access this variable only within the function. You can’t get this variable once you get out of it.

#Block scope

When you declare a variable with const or let within a curly brace ({}), you can access this variable only within that curly brace.

1 Like