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

  • Home
  • SEARCH
  • 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 824205
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T03:03:58+00:00 2026-05-15T03:03:58+00:00

I’m reading Javascript: The Good Parts and am totally baffled by what’s really going

  • 0

I’m reading “Javascript: The Good Parts” and am totally baffled by what’s really going on here. A more detailed and/or simplified explanation would be greatly appreciated.

// BAD EXAMPLE

// Make a function that assigns event handler functions to an array  of nodes the wrong way.
// When you click on a node, an alert box is supposed to display the ordinal of the node.
// But it always displays the number of nodes instead.

var add_the_handlers = function (nodes) {
    var i;
    for (i = 0; i < nodes.length; i += 1) {
        nodes[i].onclick = function (e) {
            alert(i);
        }
    }
};

// END BAD EXAMPLE

The add_the_handlers function was intended to give each handler a unique number (i). It fails because the handler functions are bound to the variable i, not the value of the variable i at the time the function was made:

// BETTER EXAMPLE

// Make a function that assigns event handler functions to an array of nodes the right way.
// When you click on a node, an alert box will display the ordinal of the node.

var add_the_handlers = function (nodes) {
    var i;
    for (i = 0; i < nodes.length; i += 1) {
        nodes[i].onclick = function (i) {
            return function (e) {
                alert(i);
            };
        }(i);
    }
};

Now, instead of assigning a function to onclick, we define a function and immediately invoke it, passing in i. That function will return an event handler function that is bound to the value of i that was passed in, not to the i defined in add_the_handlers. That returned function is assigned to onclick.

  • 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-05-15T03:03:59+00:00Added an answer on May 15, 2026 at 3:03 am

    I think this is a very common source of confusion for newcomers to JavaScript. First I would suggest checking out the following Mozilla Dev article for brief introduction on the topic of closures and lexical scoping:

    • Mozilla Dev Center: Working with Closures

    Let’s start with the bad one:

    var add_the_handlers = function (nodes) {
    // Variable i is declared in the local scope of the add_the_handlers() 
    // function. 
       var i;
    
    // Nothing special here. A normal for loop.
       for (i = 0; i < nodes.length; i += 1) {
    
    // Now we are going to assign an anonymous function to the onclick property.
           nodes[i].onclick = function (e) {
    
    // The problem here is that this anonymous function has become a closure. It 
    // will be sharing the same local variable environment as the add_the_handlers()
    // function. Therefore when the callback is called, the i variable will contain 
    // the last value it had when add_the_handlers() last returned. 
               alert(i);
           }
       }
    
    // The for loop ends, and i === nodes.length. The add_the_handlers() maintains
    // the value of i even after it returns. This is why when the callback
    // function is invoked, it will always alert the value of nodes.length.
    };
    

    We can tackle this problem with more closures, as Crockford suggested in the “good example”. A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. In JavaScript, the environment of the closure consists of any local variables that were in-scope at the time that the closure was created:

     // Now we are creating an anonymous closure that creates its own local 
     // environment. I renamed the parameter variable x to make it more clear.
     nodes[i].onclick = function (x) {
    
         // Variable x will be initialized when this function is called.
    
         // Return the event callback function.
         return function (e) {
             // We use the local variable from the closure environment, and not the 
             // one held in the scope of the outer function add_the_handlers().
             alert(x);
         };
     }(i); // We invoke the function immediately to initialize its internal 
           // environment that will be captured in the closure, and to receive
           // the callback function which we need to assign to the onclick.
    

    Rather than having the callbacks all sharing a single environment, the closure function creates a new environment for each one. We could also have used a function factory to create a closure, as in the following example:

    function makeOnClickCallback (x) {
       return function (e) {
          alert(x);
       };
    }
    
    for (i = 0; i < nodes.length; i += 1) {
       nodes[i].onclick = makeOnClickCallback(i);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I am trying to understand how to use SyndicationItem to display feed which is
Seemingly simple, but I cannot find anything relevant on the web. What is the
Does anyone know how can I replace this 2 symbol below from the string
this is what i have right now Drawing an RSS feed into the php,
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but

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.