user1033600
user1033600

Reputation: 289

return statement javascript

Why is that when I return a function I can't have more code beneath it

sample

<script language="javascript">
    return compute();
    alert(1);
</script>

The alert will not work

Upvotes: 1

Views: 374

Answers (3)

Dexygen
Dexygen

Reputation: 12561

Inside of a function/closure, you can have code beneath your return statement. Specifically, function declarations that will be hoisted, so that they will be available for use by the code above the return. I use this "pattern" all the time, here is a small example from my current code base:

function msgHandlers() {
    var scope
        ,msgs;

    return {
        SET_CONTEXT: function(context) {
            scope = context.scope;
            msgs = context.messages;
        }

        ,SUBSCRIBE_ALL: function() {
            me.subscribe(scope, msgs.ITEM_PINNED, itemPinnedHandler);
        }
    }

    function itemPinnedHandler(record) {
        loadInventoryRecord(record);    
    }
}

Upvotes: 0

jefflunt
jefflunt

Reputation: 33954

The function of the return statement is twofold. First, it returns a value (in this case, a pointer to a function). Second, it is to manage control flow, which is to say, it tells the browser that's executing that code to leave that function, and return execution control to the piece of code that called your example script.

To say it another way, trying to return a value, while also expecting to continue execution, makes it ambiguous to the browser what to do next.

If you were to flip the two lines (alert first, THEN return a value), that would cause both lines to be executed.

This tutorial may also provide further insight.

Also, as Rob W and Kris Krause noted, you can only return from a function, yet the code you've shown is not wrapped in a function.

Upvotes: 2

Kris Krause
Kris Krause

Reputation: 7326

The alert will not work

Sounds right to me. I envision this code as:

    (function() {
      return compute();
      alert(1);
    })();

Upvotes: 3

Related Questions