Value of I in this code

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

I am not able to understand how the value of i becomes 3 at any point in this piece of code

Because scope of var is global, not same let and const (ES6)

FOR stops when i = 3.

Try below codes and you see the difference:

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

So For loop stops when i = 3, so printNumTwo is 2 when the loop runs last. How did it become 3?

in the same way if you write console.log(i) after the loop it will print 3.
variables declared with var are function scoped, that means that as it is not declared inside a function everything see the variable i in the moment that code is executed. The function call is executed after the loop so it sees i having a value of 3

this is to show the difference between variables declared with let and var, they behave differently