0

I'm struggling to understand the syntax of this:

(function(abc, $, undefined) {

        // some code

}(window.abc = window.abc || {}, jQuery ));
  1. What does undefined do?
  2. what does the window.abc = window.abc || {} do?
  3. If this is a self-invoking function, why does the bracket ) close not after the function code but after the second pair of brackets?

Many thanks

  • That is an IIFE(Instantly Invoked Function Expression). Its used allot in jQuery modules. Its a great way of scoping your module so you do not leak to the global namespace. It allows you to alias variables. I believe undefined can be overwritten, however the variable undefined never has anything passed in so it means undefined is undefined incase someone outside your module decides to overwrite it. – ste2425 Jan 22 '16 at 14:22
  • http://stackoverflow.com/questions/3384504/location-of-parenthesis-for-auto-executing-anonymous-javascript-functions is a duplicate of the third question. – Quentin Jan 22 '16 at 14:24
  • @Quentin Fair enough. Or you can provide the link of those questions to non-gold JS users to close and then you can hammer with other dupe. That'll show the question as dupe of two. – Tushar Jan 22 '16 at 14:25
  • [this](http://stackoverflow.com/questions/2100758/javascript-or-variable-assignment-explanation) and [this](http://stackoverflow.com/questions/11791412/object-equals-self-or-empty-object) are related to the second question. – Quentin Jan 22 '16 at 14:26
  • Almost got it, thanks. There are some things I still don't understand: in the second question, I don't understand what the expression window.abc=window.abc and the empty brackets {} mean. Regarding the first question, does it ever happen that the 'undefined' is defined? What is the reason for 'protecting' it this way? – Natalija Gatta Deluna Jan 22 '16 at 15:09
  • "Regarding the first question" — What does the first sentence of the accepted answer on the duplicate question say? – Quentin Jan 22 '16 at 15:40
  • http://stackoverflow.com/questions/9699064/what-do-curly-braces-in-javascript-mean – Quentin Jan 22 '16 at 15:41
  • it says "The undefined is a normal variable and can be changed simply with undefined = "new value"; " this tells me it can be done but does it actually happen a lot? why would someone write a code to define undefined? – Natalija Gatta Deluna Jan 22 '16 at 16:23

0 Answers0