Explain Codes LogoExplain Codes Logo

How do I declare a namespace in JavaScript?

javascript
prompt-engineering
best-practices
functions
Nikita BarsukovbyNikita Barsukov·Nov 5, 2024
TLDR

Create a namespace in JavaScript by establishing an object to encapsulate your properties and methods:

var MyApp = { doSomething: function() { /* ... */ }, value: 42 };

Reach its members via the dot notation:

MyApp.doSomething(); console.log(MyApp.value);

This method assists in preventing naming collisions and keeping the global scope tidy.

Packing with IIFE for privacy

Control the scope of your namespace using Immediately Invoked Function Expressions (IIFE), serving as the private basement of your namespace mansion:

var MyApp = (function() { // These bad boys stay hidden in the basement var privateValue = 1; function privateMethod() { // Just a secret handshake } // The mansion's ground floor: public and proud return { doSomething: function() { // Sneak down to the basement privateMethod(); }, value: privateValue }; })();

IIFEs help to encapsulate code and control what is revealed to the outside scope.

Safe extension of namespaces

Curious on how to expand an existing namespace without running the risk of painting over it? The logical OR operator is your friend:

var MyApp = MyApp || {}; MyApp.Utils = (function() { function aUtilityFunction() { // Utility huh, so the dishwasher? } // Let's keep one foot in public return { aPublicMethod: aUtilityFunction }; })();

This approach ensures the namespace's existence and avoids unwanted rewrites.

Namespacing modularized

Embrace the module pattern to craft namespaces indicating public and private elements, while keeping everything neat and organized:

var MyApp = MyApp || {}; MyApp.Module = (function() { var _privateVar = "hush-hush"; var publicVar = "hear ye, hear ye!"; function _privateMethod() { // Narnia's gate, only for the special ones } function publicMethod() { _privateMethod(); } // Here be the loudmouths return { publicMethod: publicMethod, publicVar: publicVar }; })();

The undefined bouncer

In an IIFE, pass undefined to ensure it keeps its original value and guards against reassignments:

(function(undefined) { var safeUndefined = undefined; // Welcome to the panic room, only undefined is allowed here })();

This comes in handy when dealing with libraries or scripts that might alter undefined.

Sorting functions in namespaces

Organize your functions in a way that improves their accessibility and readability:

// Before: MyApp.doA(); // let's do A MyApp.doB(); // done with A, let's do B MyApp.doC(); // done with AB, now let's do C // After: MyApp.tasks = { doA: function() { /*...*/ }, // I'm task A, nice to meet you doB: function() { /*...*/ }, // Hi, I'm task B, need a hand? doC: function() { /*...*/ } // Hey folks, task C reporting for duty };

This arrangement groups tasks logically within a sub-namespace, thus enhancing structure.