-1

I was reading an article explaining function prototyping and inheritance in JavaScript when I came across these lines of code I can't wrap my head around

a = {} 
(function(){}())

What exactly do these lines do?

Cup of Java
  • 1,769
  • 2
  • 21
  • 34
  • That's **two** lines of code. Which is the one you don't understand? (The code does pretty much nothing, however.) – Pointy Jun 30 '17 at 17:19
  • 1
    _You don't generally wrap your head around it, but you wrap your temporary code inside that!_ It's an IIFE. `:D` – Praveen Kumar Purushothaman Jun 30 '17 at 17:20
  • Why the downvote? and I'm more interested in the second line – Cup of Java Jun 30 '17 at 17:21
  • 1
    The second line of code is is an IIFE as the comment above says: IIFE = **I**mmediately-**I**nvoked **F**unction **E**xpression. IIFE's can have a lot of uses, such as creating a closure for your code. Check out https://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1 – Joe Lissner Jun 30 '17 at 17:26

1 Answers1

3
a = {} // Be 'a' an empty object (But why ?)

function(){   // Declare a function that says Hello when it's called
   alert("Hello");
}

function(){   // Declare a function that says Hello and execute it immediately with ()
   alert("Hello");
}()

function(){}()   // Declare a function that...does nothing, and execute it immediately with ()... But apparently you can't, that's a syntax error (Thanks @pointy)

(function(){}()) // Makes it work (no syntax error)
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • The second-to-last example is a syntax error; that's what the added parentheses are for. – Pointy Jun 30 '17 at 17:28
  • So is `a = {}` affected by the second line at all? – Cup of Java Jun 30 '17 at 17:33
  • When a statement *starts* with the `function` keyword, it's a function declaration statement and following with `()` is the error part. So yes I guess it's better now :) – Pointy Jun 30 '17 at 17:33
  • @CupofJava no it is not; the two statements are independent and don't affect each other at all. – Pointy Jun 30 '17 at 17:34
  • @Pointy thank you, the lack of a semi colon really threw me off – Cup of Java Jun 30 '17 at 17:34
  • 1
    @CupofJava semicolons are generally optional in JavaScript (but please use them anyway for reasons that should be obvious to you now :) – Pointy Jun 30 '17 at 17:35