2

I have this code:

function ready() {
  $("#my_form").on("submit", function (e) {
    for (var j in someItems) {
      var element = $(someItems[j]);
      $("<input>").attr({type: "hidden", name: element.attr("name"), value: element.val()}).appendTo($(this));
    }

    for (var i = 0; i < someItems2.length; i++) { 
      // "element" is visible here ??????
      $("<input>").attr({type: "hidden", name: element.attr("name"), value: element.val()}).appendTo($(this));
    }
  });
});

jQuery(document).ready(ready);
jQuery(document).on("page:load", ready);

Why is the variable element visible in the second loop?

Incerteza
  • 32,326
  • 47
  • 154
  • 261

1 Answers1

0

Because the variables does not have block scope in JavaScript but functional scope

Please refer to this article.

Sarbbottam
  • 5,410
  • 4
  • 30
  • 41