Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8818849
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T05:12:30+00:00 2026-06-14T05:12:30+00:00

I am having some confusion regarding this Closure thing. I have two separate codes

  • 0

I am having some confusion regarding this Closure thing. I have two separate codes below that look similar but their output are different.

function setup(x) {
var array = [];
for(var i=0;i<arguments.length;i++){
    array[i]= arguments[i];
}
return array;
}
console.log(setup('a','b'));  // will output ["a","b"] 

--------------
function f() {
var i, array = [];
for(i = 0; i < 3; i++) {
    array[i] = function(){
        return i;
    }
}
return array;
}

var a = f();                 
console.log(a());       //output: [function(),function(),function()]
console.log(a[0]());    //output: 3 //same output in a[1]() and a[2]() calls as well

Now my question is, how come the output is different? both of the codes above return an array. in the first code, it prints all elements in array correctly whereas in the second code, why doesn’t it print [1,2,3]???

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T05:12:31+00:00Added an answer on June 14, 2026 at 5:12 am

    In JavaScript, you have function statements and function expressions. The first declare named functions, the latter evaluate to a named or anonymous function. You’re using a function expression.

    What I think you want to do is a call expression. All you have to do is to immediately call your function that returns i.

    function f() {
        var i, array = [];
        for (i = 0; i < 3; i++) {
            // The extra parentheses around the function are unnecessary here.
            // But this is more idiomatic, as it shares syntax with how function
            // expressions are introduced in statements.
            // I.e. you could just copy-paste it anywhere.
            array[i] = (function () {
                return i;
            })(); // don't rely on automatic semicolon insertion
        }
        return array;
    }
    

    Also note that, in your problematic example, all closures return 3 because all of them capture the same variable i.

    EDIT: To make the previous paragraph more clear, if you really wanted to have 3 distinct closures, you’d have to create a new scope for each one. Unlike other languages, Javascript doesn’t create scope just by opening a block. It only creates scope in functions. Here are two ways of doing this:

    function f() {
        var i, array = [];
        for (i = 0; i < 3; i++) {
            // With a parameter in an inner function
            array[i] = (function (n) {
                return function () {
                    // A new n is captured every time
                    return n;
                };
            })(i);
        }
        return array;
    }
    
    function f() {
        var i, array = [];
        for (i = 0; i < 3; i++) {
            array[i] = (function () {
                // With a variable in an inner function
                var n = i;
                return function () {
                    // A new n is captured every time
                    return n;
                };
            })();
        }
        return array;
    }
    

    The next example, however, is wrong, because even though n is declared in the for block, it will be as if it has been declared at the top of the function and only initialized in the for block. Remember, this is JavaScript, not Java, not C, not C#, not <whatever bracketed language>:

    function f() {
        var i, array = [];
        for (i = 0; i < 3; i++) {
            var n = i;
            array[i] = function () {
                return n;
            };
        }
        return array;
    }
    

    Equivalent code:

    function f() {
        var i, array = [];
        var n;
        for (i = 0; i < 3; i++) {
            n = i;
            array[i] = function () {
                return n;
            };
        }
        return array;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I still have some confusion about this thing. What I have found till now
I'm having some real confusion about events in c#... if I have this code
I'm having some confusion if a VOIP App can have multiple tcp sockets monitored
Removed the C tag, seeing as that was causing some confusion (it shouldn't have
I am having some confusion regarding Deleting the top N Rows order by some
I'm having some confusion between several JS structures, one of them is this one:
I am having some confusion with the new keyword,things work fine when I am
ASP.NET Application I am having some confusion with showing images. IE is fully working
Having some trouble with R's garbage collection, when passing objects to C++. We have
I have been having alot of trouble with this stupid struct. I don't see

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.