Variable Scope

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ieming.chen@gmail.com

    Variable Scope

    I have a very puzzling question about how JavaScript variable scope
    works.

    var s = 1;

    alert (s); // show s = 1

    function show ()
    {
    alert(s); // show s = undefined, expecting s= 1

    var s = 2;
    alert(s); // show s = 2
    };

    Can anybody explain why it is happening this way?

  • Joost Diepenmaat

    #2
    Re: Variable Scope

    timothytoe <timothytoe@gma il.comwrites:
    On Feb 12, 12:34 pm, Joost Diepenmaat <jo...@zeekat.n lwrote:
    >>>Variable scope in java is function-based.
    >
    You meant JavaScript, not java.
    Oops. Yes, obviously. :-)
    ieming, you might want to do what I do--declare all variables at the
    top of their functions so that you and JavaScript have the same
    understanding of the situation.
    That's probably good advice.

    --
    Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/

    Comment

    Working...