0

I read this on the javascript garden site. Can someone explain how it works?

!function(){console.log("hi")}()
user566245
  • 4,011
  • 1
  • 30
  • 36
  • 5
    ...clicked on your question, read it, performed a search, found a match, copied the url, clicked `close` link, pasted the url, voted to close... all before your question was 1 minute old. –  May 10 '13 at 19:55
  • 1
    @squint - Now if you say that you were doing this on an iPad, I'll start worshipping you right now. – Anurag May 10 '13 at 19:58

2 Answers2

2

The 'executing' parens at the end can't be done legally after a function expression. A typical (more sensical, IMO) way of writing this is with more parentheses:

(function(){console.log('hi')})()

By prepending the ! before the function expression, the JS interpreter reads the function and then runs it. This is because of the precedence of the ! operator vs. calling a function with the final ()

Alex Mcp
  • 19,037
  • 12
  • 60
  • 93
  • 1
    *"...can't be done legally after a function expression"* No, it can't be done after a function *declaration*. The invocation must be part of an expression. And why do you say the parens are more "sensical" than the `!`? –  May 10 '13 at 20:00
  • Declaration. Good catch. I should add that 'to me' it's more sensical given how parens work in other order of operation scenarios like math, that they 'bundle up' an expression, then you work from the inside out. – Alex Mcp May 12 '13 at 17:50
1

Look at this answer

tl;dr it defines a function to print out 'hi' and immediately calls it.

Community
  • 1
  • 1
yoonkwon
  • 141
  • 2