0

What does this code do? Can someone describe why the function is inside a parenthesis and also why it has a parenthesis at the end and what it is doing?

 (function (innerKey) {
                //doSomething
 }(key));
CommonSenseCode
  • 18,848
  • 28
  • 112
  • 163

2 Answers2

2

It's a self-invoking anonymous function. It will be called immediately after loading the script, and it will take the element inside the brackets key as the function's argument.

You can read more here: What is the (function() { } )() construct in JavaScript?

Community
  • 1
  • 1
kind user
  • 32,209
  • 6
  • 49
  • 63
  • what's the difference between the (innnerkey) and (key)? aren't they both arguments? – CommonSenseCode Feb 14 '17 at 14:23
  • Key is the value the outside uses as the parameter for innerkey inside the function. So innerkey is an argument, key isn't. Key is the value used for the argument innerkey. Do note that both innerkey as the function itsself are invisible to the outer scope. – Shilly Feb 14 '17 at 14:25
  • 1
    @CodingMcCodington: Same as the difference between this: `function foo(innerkey) { ... }` and this: `foo(key)`. Remove `foo` in both places, and you have just about the same thing as above. –  Feb 14 '17 at 14:26
  • @Shilly so key is then converted into innerkey? – CommonSenseCode Feb 14 '17 at 14:26
  • `key` argument can be anything, a string, a number or whatever you want. But if you want to **operate** on it inside the function's body - you will have to use it as `innerKey` variable. – kind user Feb 14 '17 at 14:26
  • 1
    @squint thanks that made it very clear :), please include answer so I can upvote – CommonSenseCode Feb 14 '17 at 14:27
  • yes. suppose this is a normal function. `function fnName( innerkey ) { ... }` To call that function you would use `fnName( key );` to invoke fnName with the value key, so that key becomes the argument innerkey inside the fn. – Shilly Feb 14 '17 at 14:27
  • 1
    @CodingMcCodington: You're welcome. The question was closed as a duplicate, so we don't really need any more answers. You'll find many more complete descriptions in some of the answers to those questions. –  Feb 14 '17 at 14:28
2

You are creating the function and invoking it at the same time with the key value filling the innerkey parameter.

Vincent J
  • 467
  • 4
  • 16