2

Despite what I've read about jQuery/JS scope, this one is still stumping me. Why is the item variable 'undefined' within the inner loop if I define it in the outer loop (or even outside of the outer loop)?

$(".table1 tbody tr").each(function() {
    var $self = $(this);
    var item = $self.find("td.item").text();
    alert(item);        //This gives the correct value.
    $(".table2 tbody tr").each(function() {
        alert(item);    //item is undefined here
    }); 
});

I'm hoping the item variable could be passed seamlessly from the outer loop into the inner loop, but clearly I'm missing something. Any explanation would be much appreciated.

3
  • 3
    Could you show a working example of the problem. Using an approximated version of your HTML it appears to work fine: jsfiddle.net/11dwarcb Commented Jul 18, 2017 at 15:02
  • You can use the snippit functionality and edit your question with a working code sample. Commented Jul 18, 2017 at 15:03
  • Rory, I noticed in your jsfiddle that the first alert prints "Foo" and the second prints "Bar". I wouldn't expected this behavior since the item variable is defined in the outer loop, I figured it should print "Foo" again (which in the case of my code is what I'm hoping to do as well). Is this not the case, and if so, what needs to be done to properly get the value from the outer loop into the inner loop? EDIT: My mistake, I'm now noticing that it prints "Foo" each time. Commented Jul 18, 2017 at 15:09

1 Answer 1

1

So, I figured it out. While my code above was incomplete, this jsfiddle resembles my actual code more closely and also reproduces the issue: https://jsfiddle.net/11dwarcb/5/

$(".table2 tbody tr").each(function() {
    var $self2 = $(this);
    var item2 = $self2.find("td.itemx").text();
    alert(item); //item is undefined here
    //...Other stuff...
    if(true){
        var item = $self2.find("td.itemx").text();
    }
});

Basically, I was trying to reinitialize the item variable within the inner loop. Even though I did this after trying to print or use that variable, it was still affected. Changing the name made everything work as expected.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.