0

I see that in javascript, sometimes you can write

function thisIsMyFunction(options) {}

and u can write

var myFunction = function(input) {}

also you can write

function() {}

When are the different declaration used?

Chris Yeung
  • 2,212
  • 4
  • 24
  • 50
  • There’s also `var myFunction = function myFunction(input) {}`. – Sebastian Simon Jul 28 '15 at 03:56
  • It doesn't really matter, just how ever you prefer. – FiringSquadWitness Jul 28 '15 at 03:57
  • 1
    This has been discussed many times before. I will search for a duplicate. – jfriend00 Jul 28 '15 at 03:57
  • `function thisIsMyFunction(options) {}` - a function with name `thisIsMyFunction` and `var myFunction = function(input) {}` - a function with name `myFunction`. no difference and last `function() {}` - a function without any name just like anonymous function. – Braj Jul 28 '15 at 03:59
  • A complete guide to what you're looking for - https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/ – Aswin Ramakrishnan Jul 28 '15 at 04:00
  • @Braj Technically, `var a=function(){}` creates an _anonymous_ function _referenced_ by `a`; it’s not a named function. – Sebastian Simon Jul 28 '15 at 04:01
  • 1
    FWIW, `function() {}` by itself is a syntax error. – Felix Kling Jul 28 '15 at 04:01
  • Main difference between the first two: `function a(){}` is hoisted (you can use it as a function, even if the function is defined later in the code), whereas from `var a=function(){}` only the `var a;` part is being hoisted and it’s not a function _yet_. `(function(){})` creates an anonymous function, even if `var … =` is before it. Other than that, there isn’t much of a practical difference. – Sebastian Simon Jul 28 '15 at 04:03
  • @FelixKling thanks for correcting my understanding. – Braj Jul 28 '15 at 04:04

0 Answers0