JavaScript - Return from anonymous function (varScope)
Asked Answered
H

2

13
<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! :)

Haines answered 29/8, 2011 at 12:0 Comment(2)
Ok, I'm dumb. Just put the return before the anonymous function and done. LOL.Haines
Um, store the result of the self-execution in a variables, or just return it directly?Woodsia
R
13

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>
Rebellious answered 29/8, 2011 at 12:5 Comment(0)
M
0

Just simply put the call of anonymous function in a variable:

<script>
    var sample = function() {
        let a = (function() {  // The function returns when you call it
            return "something"
        })();
        return a;
    }
</script>
Maleeny answered 3/4, 2024 at 17:35 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.