SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Evangelist runeveryday's Avatar
    Join Date
    Jul 2009
    Posts
    437
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    why the result is NaN?

    HTML Code:
    var a = 10;
    sayHi();
    function sayHi()
    {
    var a = a + 10;
    alert(a);
    return a;
    }
    alert(a);
    alert(sayHi()+10);
    why the above result is not 20 and 30? i feel the first is 20 , then 30.in sayHi() function, there is a line var a; i don't know why the a is undefined。 thank you

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,097
    Mentioned
    153 Post(s)
    Tagged
    2 Thread(s)
    Because a is defined in the global scope and can't be reached from within your function. If you want the function to use that variable you need to pass it as a parameter, like so

    Code javascript:
    var a = 10;
    a = sayHi(a);
    function sayHi(a) {
      var a += 10;
      alert(a);
      return a;
    }
    alert(a);
    alert(sayHi(a)+10);

    Basically you now have two different a variables; one lives within the global scope while to other lives only within the function sayHi. This is probably easier to understand if the function uses a different variable name:

    Code javascript:
    var a = 10;
    a = sayHi(a);
    function sayHi(b) {
      var b += 10;
      alert(b);
      return b;
    }
    alert(a);
    alert(sayHi(a)+10);

    This is exactly the same as the above but I now use a different variable within the function; semantically they're the same thing.

    You may want to read up on variable scopes in javascript. For example http://coding.smashingmagazine.com/2...ascript-scope/
    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •