user1361747 user1361747 - 6 months ago 17
jQuery Question

How do i set a variable using conditional statements?

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>

Answer

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>