1

I've stumbled upon construct that I'm not sure what it does

var MYLIBRARY = MYLIBRARY || (function(){

https://stackoverflow.com/a/2190927/680815

I don't have much rep. yet so I can't post a comment to ask about so well, sorry for the mess. :)

Does it mean if MYLIBRARY is defined use it and if not assign encapsulated code?

Thanks,

Community
  • 1
  • 1
sebastian_t
  • 2,241
  • 6
  • 23
  • 39
  • This defines MYLIBRARY if it isn't already set. It's not assigning a reference to the function; it's invoking the function and assigning its return value. – Warty Sep 14 '14 at 00:19
  • (I'll note that "is set" isn't correct terminology, but hopefully you get the point. This pattern is often used for placing many class-like things in namespaces across many files. – Warty Sep 14 '14 at 00:27

2 Answers2

3

yes, it does pretty much what you think.

if MYLIBRARY is defined it is used, if not it is assigned the encapsulated code?

Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
PuercoPop
  • 6,707
  • 4
  • 30
  • 40
3

that checks if MYLIBRARY not undefined, null or false then keep it as it is, else it will be the function assigned.

in another words:

if (!MYLIBRARY) {
    MYLIBRARY = function(){};
}

but in your snippet I think MYLIBRARY is always undefined because you're setting the variable when you check or it's duplicating.

Raeef Refai
  • 1,471
  • 14
  • 26
  • Your code example is not equivalent because you removed the `var`, which means that it'll throw if it hadn't been previously declared. And no, `MYLIBRARY` is not always `undefined` unless this code happened to be inside a function. Seems more likely to be global. – cookie monster Sep 14 '14 at 02:01
  • 1
    if MYLIBRARY is global then why to re-declare it? you think that is right? whatever, I said: "I think" which means it depends on the code before. – Raeef Refai Sep 14 '14 at 02:09
  • Well, that's the whole point. If it's global, but it may or may not be defined, then you use the technique in the question. For a local, it doesn't make sense unless it's a function parameter that may or may not have received a value. – cookie monster Sep 14 '14 at 04:33