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
});
1
  • Yes, I see that it is, however, Igor's answer below about "redeclaring" the variable inside the function was right to the point. Commented Jun 5, 2013 at 15:06

1 Answer 1

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.

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

3 Comments

gsd isn't global...
so, the outer scope should be gsd="", instead of var gsd=""?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.