views:

115

answers:

1

I'm having trouble with Global variables in Javascript. From every article I've read a variable declared out of a function has a complete scope. But bellow;

var leftMargin = 36;

alert(leftMargin); /* '36' */

function position(direction) {

    alert(leftMargin); /* 'undefined' */

}
+5  A: 

A you positive it's undefined ?

<script type="text/javascript">
var leftMargin = 36;
alert(leftMargin); /* '36' */
function position(direction) {

    alert(leftMargin); /* '36' */
}
position(); 
</script>

Alerts 36 twice for me, as expected. It might be unset between defining the leftMargin variable and actually calling position().

Martijn Laarman
Ah yes, it was something else within the function which was spoiling it. I should learn to strip the code down and work back up :)Thanks for your time.
Ben