Namespace

Situation: 

You have different code from different sources, like jQuery, Bootstrap, and a mapping library. You want to ensure that your own code doesn't interfere with other code.

Actions: 

Create a namespace for your own code.

Explanation: 

Usually, you have different JS code from different sources. For example, jQuery, Bootstrap, a mapping library, and your own code.

You want to ensure that your own code doesn't interfere with the rest of the code. You need unique variable and function names for your own code.

Namespaces solve the problem:

  1. <script>
  2.     "use strict";
  3.     var YourNamespace = YourNamespace || {};
  4.     (function($) {
  5.         ...
  6.     }(jQuery));
  7. </script>
YourNamespace is unique for your project. When you define functions, map them into the namespace:

YourNamespace.append = function() {
    ....
}

Call your function like this:

YourNamespace.append();

jQuery also has an append() function. Your function won't collide with it, because your function is in your namespace.

The lines…

(function($) {
    ...
}(jQuery));

… make sure that jQuery can use $ as a function name.

Referenced in: