Js issue regarding using let and var

Please look at the following two Javascript codes and their answers:


var printNamm;
for (var w = 0; w < 3; w++) {
  if(w === 2){
    printNamm = function() {
      return w;

Returns => 3



let printNa;
for (let x = 0; x < 3; x++) {
  if(x === 2){
    printNa = function() {
      return x;

Returns => 2

Can anyone explain me the reason of this difference?

it is happening due to the scope of variable w . in this case it is declared with var keyword , that makes it having global scope and it is accessible outside of for loop. at some point w equals 2 and w++ happends, for loop body is not executed, but the value of w is set to 3 anyway and it is accessible in that function with name printNamm .

variable scope

hi. this same topic is discussed in this challenge https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords/