Namespaced Objects
A namespace is an object that holds a group of related variables and functions as its properties. Instead of declaring items, add and total as separate global names, a script declares one object, such as BASKET, and puts them inside it, so the script adds a single name to the global scope.
The problem this solves is collisions. Every classic <script> on a page shares one global scope, so if two scripts both declare a function called total, the second one replaces the first, or with let and const the page throws a SyntaxError. Keeping each script’s names inside its own object makes this much less likely.
Declaring a namespace
Section titled “Declaring a namespace”A namespace is an ordinary object literal. Its methods refer to the object’s other properties through this.
const BASKET = { items: [], add(name, price) { this.items.push({ name, price }); }, total() { return this.items.reduce((sum, item) => sum + item.price, 0); }, describe() { return `${this.items.length} items, £${this.total().toFixed(2)}`; },};
BASKET.add('Teapot', 18.5);BASKET.add('Tea towel', 6);console.log(BASKET.describe());This prints:
2 items, £24.50Namespace names are often written in capitals, so that they stand out from ordinary variables, but that is only a convention.
Nesting namespaces
Section titled “Nesting namespaces”A larger program can nest one namespace inside another, which groups the code by area while still adding only one global name.
const SHOP = { format: { price: (pence) => `£${(pence / 100).toFixed(2)}`, }, stock: { levels: { teapot: 4, mug: 0 }, inStock(product) { return (this.levels[product] ?? 0) > 0; }, },};
console.log(SHOP.format.price(1850));console.log(SHOP.stock.inStock('teapot'), SHOP.stock.inStock('mug'));This prints:
£18.50true falseInside inStock, this is SHOP.stock, because that is the object the method was called on, not SHOP.
Losing this
Section titled “Losing this”this depends on how a method is called, not on where it was written. Copying a method out of its object and calling it on its own loses the object, which also happens when a method is passed as a callback.
const BASKET = { items: ['Teapot', 'Tea towel'], describe() { return `${this.items.length} items`; },};
const describe = BASKET.describe;try { console.log(describe());} catch (err) { console.log(`${err.name}: ${err.message}`);}
const bound = BASKET.describe.bind(BASKET);console.log(bound());This prints:
TypeError: Cannot read properties of undefined (reading 'length')2 itemsThe plain call sets this to the global object, which has no items property, and in strict mode this would be undefined and the error would come one step earlier. bind() returns a copy of the function with this fixed to the object. The other common fixes are to wrap the call in an arrow function, as in () => BASKET.describe(), or to write BASKET rather than this inside the methods. The this Keyword covers the rules in full.
A namespace on a page
Section titled “A namespace on a page”In the browser, a namespace usually has an init method that finds the elements and attaches the listeners. When a method is passed straight to addEventListener(), this inside it is the element, not the namespace, so this example attaches arrow functions instead.
<button id="add-mug">Add a mug (£7.50)</button><p id="summary">Basket is empty</p>const BASKET = { items: [], init() { this.summary = document.getElementById('summary'); document.getElementById('add-mug').addEventListener('click', () => this.add('Mug', 7.5)); }, add(name, price) { this.items.push({ name, price }); const total = this.items.reduce((sum, item) => sum + item.price, 0); this.summary.textContent = `${this.items.length} items, £${total.toFixed(2)}`; },};
BASKET.init();Each click adds a mug and updates the paragraph, so the second click shows 2 items, £15.00. The arrow function has no this of its own, so it uses the this of init, which is BASKET.
Namespaces today
Section titled “Namespaces today”A namespace object keeps names apart, but it does not hide anything, because every property can be read and changed from outside. IIFEs vs Namespaced Objects shows how to keep some values private. In current code, ES modules do both jobs: each module has its own scope, so its top-level names never reach the global scope, and it shares only what it exports. Namespace objects are still useful inside a module to group related functions, and in small pages that use classic scripts.
Steve Griffith covers this topic in his video JavaScript Namespaces.