0

I've a code:

var myFn = function(){
  //some code
}
myFn();

So I have to define a function, then run it in two rows. Is there a way to define a function (with storage it in variable) and run it instantly, in one expression? Just a short way of this.

Mikhail Kopylov
  • 2,008
  • 5
  • 27
  • 58
  • 3
    https://en.wikipedia.org/wiki/Immediately-invoked_function_expression – j08691 Apr 08 '16 at 16:04
  • Yes, add a couple of parenthesis after those braces; – Brad Christie Apr 08 '16 at 16:04
  • Ummm... why? What problem are you trying to solve here? Usually you either want to declare a function and run it at a different place in code, or you just want to run an anonymous function. If you really want to do this, just follow the usual rules of the language - assignment returns the assigned value, so you can do `(myFn = function() { ... })();`. The original variant is much more readable, though. Are you trying to write obfuscated code? If not, I'd avoid such "shortcuts", and just use a separate declaration and invocation. – Luaan Apr 08 '16 at 23:01
  • I'd like to have function to call it in other places, but it should be run first time just after creating. Now I write separate declaration and invocation, and want to shorten the code – Mikhail Kopylov Apr 09 '16 at 04:22

1 Answers1

-1
var myFn = function(){
  console.log("test");
}()

myFn will be undefined because the function doesn't return anything

Sumama Waheed
  • 3,579
  • 3
  • 18
  • 32
  • Be careful assigning the result to `myFn` as done here - this will assign the _results_ of executing the function to `myFn`, rather than the function itself (as in the original question) – Krease Apr 08 '16 at 21:56
  • oh didn't know that..interesting..thanks – Sumama Waheed Apr 08 '16 at 22:40