Var vs. let question

Tell us what’s happening:
I’m fine on the challenge.

I’m just still confused as to why the var version returns 3 for ```
console.log(printNumTwo())


If someone could send me a link that might explain this in a bit more detail that would be great.

var printNumTwo;
for (var i = 0; i < 3; i++) {
if (i === 2) {
printNumTwo = function() {
return i;
};
}
}
console.log(printNumTwo());
// returns 3


'use strict';
let printNumTwo;
for (let i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns "i is not defined"

Thanks,
Zak

The main difference between var and let is it’s scope.
Var can take things globaly and count function/other elements with it same name . Which might explain the extra number? you had as an outcome
Let only will keep to one code block. So it’s more limited.

Hello there @zakzd808 :wave:, welcome to FCC Forums…

As @KittyKora explained, the main difference of var and let is scopes. Scopes is where it can be accessed in. I will add const explanation just for the sake of it.

var is function scoped. That means if you didn’t put it inside a function, it will be a global variable and you can access it anywhere in your code. If it’s inside a function, it can only be accessed inside the function.

let and const is an addition from ES6/ES2015/EcmaScript2015 with other features added.

let in the other hand is block scoped. What is block? In JavaScript a block is usually determined by curly braces { }, here’s a link to a better explanation about block:


So if a let is declared inside a block, it can only be accessed inside that block. Ex:
let five = 5;
if(five == 5) {
  let fifty = 50;
  console.log(fifty); //returns 50
  console.log(five);//returns 5
}
console.log(fifty); // returns: Reference Error: 'fifty' is not declared.
console.log(five);//returns 5

const has the same scope as let, it is block scoped, but the twist is that const is a constant variable as the name suggests. That means you cannot modify the value of the variable. You can mutate it and you will learn this later. Here’s more information about const:

Hope this helps :slight_smile:

Sorry for the late reply, but thanks so much for your detailed response. I really appreciate it.