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 8189807
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T03:24:24+00:00 2026-06-07T03:24:24+00:00

Interesting issue here, optimising some code but am having trouble with scope issues using

  • 0

Interesting issue here, optimising some code but am having trouble with scope issues using a javascript loop as opposed to a jQuery loop.

If for example we have 3 “decade” iterations, with values “1950”, “1960”, and “1970”, using the javascript loop, we would get “1970” (the last iteration in the loop) all the time on the “alert” of decade.name, but using jQuery.each we get the expected value for each created element.

Questions:
– why does this work with jQuery.each and not regular javascript loop?
– how can i make this work with a normal javascript for loop?

$.ajax({
    async: true,
    type: 'post',
    url: 'ajax/products.php',
    data: {
        'action': 'get_filter_decades',
        'data': {
            "search_term": ple.find('input[name="search_term"]').val(),
            "first_letter": $.bbq.getState('first_letter'),
            "category_id": categoryId.val(),
            "original_release_year_range": ple.find('input[name="original_release_year_range"]').val()
        }
    },
    success: function (jsonResponse) {
        if (jsonObj = handleJsonResponse(jsonResponse)) {
            var filterDecadesResultList = filterDecades.find('ul.decade_result_list');
            filterDecadesResultList.hide();
            filterDecadesResultList.empty();

            var originalReleaseYearRange =     $(ple.find('input[name="original_release_year_range"]'));

            // jquery loop
            //$( jsonObj.data.decades ).each( function( i, decade ) {

            // javascript loop (faster!)
            var decadesLength = jsonObj.data.decades.length;
            var listElement;
            var linkElement;
            var decade;

            for (var i = 0; i < decadesLength; i++) {
                decade = jsonObj.data.decades[i];
                listElement = $('<li />');
                linkElement = $('<a />');
                linkElement.text(decade.name);

                if (decade.product_count > 0) {
                    linkElement.append(' (' + decade.product_count + ')');
                    if (decade.selected) {
                        linkElement.addClass('selected');
                    }
                    linkElement.on("click", function () {
                        alert(decade.name);

                        if (!linkElement.hasClass('selected')) {
                            originalReleaseYearRange.val(decade.name);
                            $.bbq.pushState({
                                'original_release_year_range': decade.name
                            });
                            productListPaginate(ple);
                        } else {
                            originalReleaseYearRange.val('');
                            $.bbq.removeState('original_release_year_range');
                            productListPaginate(ple);
                        }
                    });
                }

                listElement.append(linkElement);
                filterDecades.find('ul.decade_result_list').append(listElement);
                // jquery loop
                //});

                // javascript loop
            }

            filterDecadesResultList.show();
        }
    }
});
  • 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-07T03:24:26+00:00Added an answer on June 7, 2026 at 3:24 am

    Consider the following sample: http://jsfiddle.net/9vZUg/1/

    var years = [2010, 2011, 2012];
    for (var i=0; i<years.length; i++) {
        var year = years[i];
        var input = document.createElement("input");
        input.type = "button";
        input.value = year;
        input.onclick = function(){
            alert(year); // at this point year will be always be 2012
        }
        document.body.appendChild(input);
    }​
    

    That happens because we create function at one point but use it later on. And at the moment we are calling it year is always 2012 as it was on the last iteration.
    How can we fix it? Create closure:

    var years = [2010, 2011, 2012];
    for (var i=0; i<years.length; i++) {
        (function(){
            var year = years[i];
            var input = document.createElement("input");
            input.type = "button";
            input.value = year;    
            // now year is stored here and would be unique for each handler
            input.onclick = function(){
                alert(year);
            }
            document.body.appendChild(input);
        })();
    }​
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I ran across an interesting issue in some of my humanize_bytes() code. This loop
I'm having an interesting JNA issue here. Under JRE 1.6 and 1.7 x64, I
Here is an interesting issue I noticed when using the Except Operator: I have
Ok, so I was having a very interesting issue with CakePHP 1.3, in that
I'm having an interesting issue with Leptonica that I'm wondering if other SO members
I have a string like this: Heading Some interesting text here HeadingSome interesting text
Happy Friday. Having an interesting time debugging a zombie issue. I have a UITableView
Folks, I'm having an interesting issue with Silverlight DataGrid data binding. It may be
I have an interesting problem to solve here that may require some creative direction.
I am facing some critical issue which might be interesting for whom , those

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.