-2

In a Javascript programming community, someone asked "How to declare anonymous method and run it immediately?" then others answered (function(){})() and (function(){}()).
People who answered (function(){}()) says that is correct and it's possible to run, but ideone says that is wrong and I think that is incorrect.
Following links are for comparison between SpiderMonkey and Rhino.
http://ideone.com/rKaYtW
http://ideone.com/Lblb7w

Is (function(){}()) really correct on Javascript?

  • Define "correct". If you mean if it's valid syntax, yes it is (only if in enclosed in parentheses as an expression). – Andrew Li Mar 24 '17 at 04:05
  • @AndrewLi Thanks, I let them know about it. – LesMiserables25 Mar 24 '17 at 04:06
  • 1
    Also, your error on IDEONE was the result of leaving out a semicolon between the two IIFEs. Because you left out a semicolon and JavaScript saw that the next token was a (, it interpreted the other IIFE as an invocation of the previous function's return value with a callback, which was wrong. – Andrew Li Mar 24 '17 at 04:08
  • http://stackoverflow.com/questions/26078006/iife-with-unary-operator-real-world-use-case/26078333#26078333 – Bhojendra Rauniyar Mar 24 '17 at 04:11

1 Answers1

3

"but ideone says that is wrong"

If you are talking about the error in the links you show, that's because you didn't separate the two examples with a semicolon, so the second one is having its outer set of parentheses interpreted as a function call of the previous expression.

(function(){
    print("This is what I want.")
})() // <<< no semicolon causes the error here
(function(){
    print("This may be what I want.")
}())
zippy dippy
  • 256
  • 1
  • 4