3
<script>
    window.something = (function(){
        return function(x){
        console.log(x);

        };  


    })();

    something("hello");
</script>

Just wondering, why is the parameter "hello" passed to the function inside the something function which has no parameter? Also, why doesn't the something function execute immediately? Its a self-invoking function but its strange that I have to call it first before it can execute.

Nigel
  • 73
  • 6
  • 1
    Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Andreas Aug 13 '17 at 10:28
  • The function without the parameter is not "the something function". It's an IIFE that *returns* the `function(x) {…}` that will become `something`. – Bergi Aug 13 '17 at 12:16

3 Answers3

2

You are directly calling the function, also known as the module pattern.

So when having this code

something = (function(){
    return function(myparam) {
        // ...
    };  
})();

it is equivalent to this code:

something = function(myparam) {
    // ...
};
user3151902
  • 3,154
  • 1
  • 19
  • 32
1

something is the result of an immediately-invoked function expression that returns the internal function. You then call that internal function with "hello".

orip
  • 73,323
  • 21
  • 116
  • 148
1

This is how closure works. You can a function and then again call the function with parameter for return function. Take a look at this example:-

function multiply(num1) {
  return function(num2) {
    return num1 * num2;
  };
}

var multi = multiply(2);
console.log(multi(5));

Now , as you can see we stored the first function call in a variable called multi (which you can say is the function from the first return statement of the function multiply on line 2) and the using multi as a function we are passing it an argument for num2 .