Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ryanve
Last active February 2, 2019 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanve/3d83e1f001a4a99e25bd022be3ff1250 to your computer and use it in GitHub Desktop.
Save ryanve/3d83e1f001a4a99e25bd022be3ff1250 to your computer and use it in GitHub Desktop.
JavaScript closure patterns

IIFE (Immediately Invoked Function Expression)

!function() {
  // Code in here is encapsulated
}();

Note that ! or + is safer than () because () could invoke preceding code.

// Parens invoke the console.log
console.log
(function() { 
  return "invoked" 
}());
// Won't log anything
console.log
!function() { 
  return "invoked"
}();
// Won't log anything
console.log
+function() {
  return "invoked"
}();

! seems ideal because it like cautions that the code ahead is a closure

UMD (Universal Module Definition)

!function(root, name, make) {
  if (typeof module != "undefined" && module.exports) module.exports = make()
  else root[name] = make()
}(this, "example", function() {
  return /* api */
});
!function(name, make) {
  if (typeof module != "undefined" && module.exports) module.exports = make()
  else if (typeof window != "undefined") window[name] = make()
}("example", function() {
  return /* api */
});
!function(name, make) {
  var made = make()
  if (typeof module != "undefined" && module.exports) module.exports = made
  else if (typeof window != "undefined") window[name] = made
}("example", function() {
  return /* api */
});
@ryanve
Copy link
Author

ryanve commented Feb 2, 2019

unrelated gist image experiment...this image fit the mood =p

¡!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment