Js issue regarding using let and var

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

Code#1:

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

Returns => 3

but,

Code#2:

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

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
var
let

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/