While practicing JavaScript, I came across with one doubt I am printing variable i value using var and using let keyword and both the time getting different result but unable to understand why I need some explanation for this??
Declaring i
as let
:
<script>
(function timer() {
for (let i = 0; i <= 5; i++) {
setTimeout(
function clog() {
console.log(i);
}, i * 1000
);
}
})();
</script>
The output is a count from 0 to 5:
Declaring i
as var
, on the other hand:
<script>
(function timer() {
for (var i = 0; i <= 5; i++) {
setTimeout(
function clog() {
console.log(i);
}, i * 1000
);
}
})();
</script>
The output is 6 times a 6: