0

This does not work, even though putting a simple print ("foo") in the function block does work.

<script>

var viewportHeight = $(window).height();
var X;

$(function() {

    if (viewportHeight >= 600) {
         var X = 100;
       }
});
</script>
1
  • you have 2 different X variables, delete the second var. Commented May 15, 2012 at 18:37

2 Answers 2

8

The var keyword is used to create a variable whose scope is assigned to whatever function it is in. If it is not inside a function, its scope is the window, making it a global variable. If you omit the var keyword, the js engine will look up the scope chain for the closest definition of the variable. So, by using var inside the function, you are creating a new variable called X that is local to that function. If you omit the var keyword inside the function, it will look up the scope chain and find the var X that you defined above.

<script>

var viewportHeight = $(window).height();
var X;

$(function() {

    if (viewportHeight >= 600) {
        X = 100; //don't use var if you want to access the above X
    }
});
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

PS. This works because redefining in function scope results in the creation of a local variable, different from the one defined outside the function. Look out for closure.
@user1361747 Glad it worked! Be sure to mark the question as answered
2

Just my two cents, but you could write this whole thing as a single expression.

  var X = $(window).height() >= 600 ? 100 : null;

this seems like a place for good oll shorthand

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.