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 3 of 3
  1. #1
    New Coder
    Join Date
    Apr 2009
    Posts
    29
    Thanks
    1
    Thanked 1 Time in 1 Post

    clarification on passing variables

    if i have:

    function someFunction(){
    var original = "Original Variable";
    anotherFunction(original);
    }

    function anotherFuntion(){
    /* 1.does the original variable automatically get passed?
    2. will var transformed = original + "Transformed"
    give me a result of "Original Variable Transformed"?
    3. Or does it have to be declared in the function: anotherFunction(original)
    */
    }

    thanks for any help

  • #2
    Regular Coder Amphiluke's Avatar
    Join Date
    Jul 2009
    Posts
    312
    Thanks
    3
    Thanked 89 Times in 89 Posts
    In your case the original variable's value will be accessible within the anotherFuntion only as a property of the arguments object
    Code:
    function anotherFuntion(){
        alert(arguments[0]); // "Original Variable"
        var transformed = arguments[0] + "Transformed";
    }
    I am still learning English

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,200
    Thanks
    75
    Thanked 4,342 Times in 4,308 Posts
    Or does it have to be declared in the function: anotherFunction(original)
    It can be. But you could also write the function as
    Code:
    function anotherFunction( frazzlemooper )
    {
        var transformed = frazlemooper + "Transformed";
        ...
    }
    The name of the function argument and then name of the parameter used when the function is called are completely independent of each other.

    **********

    I would also like to point out that if the variable original had *NOT* been declared inside of someFunction then you could write:
    Code:
    var original; // this declaration is optional
    
    function someFunction(){
        original = "Original Variable"; // notice: no var keyword!
        anotherFunction( ); // and no argument passed
    }
    
    function anotherFuntion(){
        var transformed = original + "Transformed"'
    }
    In this case, you have given the variable original PAGE SCOPE, meaning it is visibile to all functions on the page.

    You shouldn't, in general, give page scope to variables unless you really do need them to be "visible" at all times to all functions in the page. But whey you need to, you can.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

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