34

This is a simplified version of what I am trying to accomplish, but I want to pass a variable outside the scope of the function. I am declaring the variable outside the function but can't get it.

HTML:

<p>5</p>
<p>6</p>
<p>7</p>

JS:

$(document).ready(function () {
    var gsd = "";
    $("p").each(function () {
        if ($(this).text() === "5") {
            var gsd = $(this).text();
            alert(gsd); // this works
        }
    })
    alert("get var outside func" + gsd); //does not work
});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user2232681
  • 839
  • 4
  • 16
  • 33
  • Yes, I see that it is, however, Igor's answer below about "redeclaring" the variable inside the function was right to the point. – user2232681 Jun 05 '13 at 15:06

1 Answers1

38

You redeclare gsd as a new variable inside your function. Remove var in front of gsd inside the function to address the gsd in the outer scope.

Igor
  • 15,833
  • 1
  • 27
  • 32
  • 1
    `gsd` isn't global... – Ian Jun 05 '13 at 14:33
  • so, the outer scope should be gsd="", instead of var gsd=""? – user2232681 Jun 05 '13 at 14:59
  • 3
    @user2232681 - no, the first definition of `gsd` is correct for the code shown. However, its scope is the anonymous function connected to `$(document).ready`, not global. If you want to use `gsd` in other parts of javascript in the page, then either omit `var` in front of it, or declare it in the global scope - directly inside `script` tag. – Igor Jun 05 '13 at 15:04