Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Jul 2009
    Posts
    152
    Thanks
    8
    Thanked 0 Times in 0 Posts

    why the result is NaN?

    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
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,981
    Thanks
    56
    Thanked 557 Times in 554 Posts
    redeclaring "a" as a variable creates a new variable and wipes the value of the original. Remove the "var" in your function:
    Code:
    var a = 10;
    sayHi();
    function sayHi()
    {
    a = a + 10;
    alert(a);
    return a;
    }
    alert(a);
    alert(sayHi()+10);

  • Users who have thanked xelawho for this post:

    runeveryday (09-29-2012)


  •  

    Posting Permissions

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