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 4 of 4
  1. #1
    New Coder
    Join Date
    Feb 2011
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Function returns undefined

    Suppose we have following javascript codes: Case 1.

    var foo = function ()
    {
    var x = "hello";
    var bar = function () {
    alert(x);

    }
    return bar;
    }

    var bar_ref= foo();

    document.write(bar_ref()); // it pops up "hello" and print-outs "undefined".

    If we modified above code slightly, shown as follow: Case 2.
    var foo = function ()
    {
    var x = "hello";
    var bar = function () {
    alert(x);

    }
    return bar();
    }

    var bar_ref= foo();

    document.write(bar_ref()); // it only pops up "hello".


    As you can see, Case 2 modified the return value from "return bar" to "return bar()," which won't cause the "undefined" output. To me, it looks like when the JS interpreter executes the line "bar_ref();" it triggers the execution of function "foo", besides both "return bar" and "return bar()" do the same job which is to execute function body of "bar". The only difference is that after the execution of function bar, its function body does not exist anymore, so when the interpreter executes the line "return bar;" it follows the function identifier "bar" and ends up with "undefined". This is why the Case 1 gives us "undefined", but I am not quite clear about why the Case 2 can trace down to the function body of "bar". Do you have any ideas about such difference outputs?

    Dan

  • #2
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    Quote Originally Posted by danielwoods View Post
    Suppose we have following javascript codes:
    The function "bar" doesn't return anything (because alert() returns nothing).

    However, this.......

    Code:
    var foo = function () {
        var x = "hello";
        var bar = function () {
            alert(x);
            return x;
        }
        return bar();
    }
    ......works.

    You need the () after "return bar", otherwise you return the FUNCTION rather then CALL the function and run it.

    You also need to return "x" to the caller.

    This code:

    Code:
    setTimeout(function() {
        var z = foo();
        alert(z);
    }, 1000);
    Pops up "hello" twice. The first time by calling "bar" and the second time by alerting the return value from "foo".

    Make sense?
    "Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov

  • #3
    Senior Coder Rowsdower!'s Avatar
    Join Date
    Oct 2008
    Location
    Some say it's everything.
    Posts
    2,027
    Thanks
    5
    Thanked 397 Times in 390 Posts
    You have a problem with your variable scope in both examples. The only difference is that in one example you are trying to write an undefined variable while in the other you are trying to write the return of a nonexistent function. One gives you "undefined" while the other just chokes since the function does not exist (at least in the scope in which it was called).

    It looks like you're really trying to get "closures" to work here. So you want bar_ref() to be a proxy for calling foo.bar() and you want to set that up without having foo.bar() get fired. If so, try something like this:

    Code:
    var foo = (function (){
    	var x = "hello";
    	var bar = function () {
    		alert(x);
    	};
    	return {
    		//we have to actually return the functions or variables we want to use outside of this function declaration in order to make them public...
    		bar:bar
    	};
    })(); //note the empty parantheses here to auto-fire the foo() function and make our global items global...
    
    var bar_ref = function(){foo.bar()}; //here we create a reference to the foo.bar() function rather than trying to directly assign it (which ends up just firing it)...
    
    bar_ref(); // it pops up "hello"
    Note the return section in this code. In this case all we want to return is bar, but we could add any variables or functions we wanted here (separated by commas).

    Also take note of the parenthesis containing the entire declaration of the function "foo" and the empty parantheses at the end of that function declaration. These are needed in order to auto-fire the foo() function and make our desired global items available... If not for this empty set of parentheses we would have to actually call foo() explicitly later in our script in order to have the returned foo element(s) available outside of the function.

    Next look at the variable assignment of bar_ref. We don't just write bar_ref=foo.bar(); because that would actually cause foo.bar() to execute. Instead, we use the anonymous function to create a reference to foo.bar().

    Using the above, you could access bar() by either of these two methods:
    Code:
    foo.bar()
    
    //OR
    
    bar_ref();
    Last edited by Rowsdower!; 12-12-2011 at 05:42 PM. Reason: cleaning up a spelling error and adding external reference link...
    The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
    See Mediocrity in its Infancy
    It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
    Seek and you shall find... basically:
    validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

  • #4
    New Coder
    Join Date
    Feb 2011
    Posts
    10
    Thanks
    3
    Thanked 0 Times in 0 Posts
    well...I agree with your opinion on why it returns undefined, it is because the function bar does not have return statement.

    Another thing is the assignment bar_ref = foo(), this make bar_ref trigger the execution of the function foo rather than just being a reference. The output command "document.write(bar_ref);" can give us "hello". But when it outputs "bar_ref()", it actually call the function itself twice, which it equals to call like this way: "foo()();".


  •  

    Posting Permissions

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