Javascript closure problem

function makeFunctionarray(){
    const arr = [];
    for(var i = 0 ; i < 5 ; i++){
        arr.push(function() { console.log(i);});
    return arr;
const output = makeFunctionarray();
output[0]();   // so here output is 5 

i am expecting output to 0 but here i get 5 so someone please explain me

TL;DR - replace var with let.

thanks for response,
but i know that i can get 0 insted of 5 when i use let but i want to know what is happening under the hood .
why we get 5 when we use var ?

One of the links in that SO thread: Variables and scoping in ECMAScript 6

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.