1

Why this anonymous function

(function () {
  return ("i am a function")
})()

is equivalent to

function hi () {
  return ("i am a function")
}

the function work with hi()

Also why if I removed the brackets for the anonymous function it does not work

function () {
  return ("i am a function")
}()
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • Check my answer to this question: https://stackoverflow.com/questions/1634268/explain-the-encapsulated-anonymous-function-syntax/ – Christian C. Salvadó Nov 14 '19 at 14:11
  • You need to read about `IIFE` https://medium.com/javascript-in-plain-english/https-medium-com-javascript-in-plain-english-stop-feeling-iffy-about-using-an-iife-7b0292aba174 – Md Johirul Islam Nov 14 '19 at 14:14
  • 1
    If you don't use the parentheses, the function is evaluated as a Function Statement, and function statements cannot be anonymous, the name is required by the grammar. – Christian C. Salvadó Nov 14 '19 at 14:15
  • your first one is Immediately invoked function ... so when you declare a function as your hi function after you have to call with hi() ... but your last exaple doesn't work becouse you return a value but you never "call" that so if you change the last as: `myMessage=function () { return ("i am a function") }()` – Angelotti Nov 14 '19 at 15:47

0 Answers0