Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Return from anonymous function (varScope)

<script>
    var sample = function() {
        (function() {
            return "something"
        })();
        // how can I return it here again?
    }
</script>

Is there a way to return the returned value from the anonymous function in the parent function again or do I need to use a defined function to get the returned value? Thanks! :)

like image 904
headacheCoder Avatar asked Aug 29 '11 12:08

headacheCoder


People also ask

Can anonymous function return JavaScript?

No, you cannot return a value from an asynchronous callback. Event callback will be called on click, but you can't assign its result.

How do you call an anonymous function in JavaScript?

The () makes the anonymous function an expression that returns a function object. An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable. In this example, the anonymous function has no name between the function keyword and parentheses () .

Can you pass a anonymous function as an argument to another function?

They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.

Can anonymous function pass as parameter JavaScript?

Conclusion. An anonymous function is a function with no name which can be used once they're created. The anonymous function can be used in passing as a parameter to another function or in the immediate execution of a function.


1 Answers

Just put the return statement at the point where you call the function.

<script>
    var sample = function() {
        return (function() {  // The function returns when you call it
            return "something"
        })();
    }
</script>
like image 152
Quentin Avatar answered Oct 02 '22 23:10

Quentin