Skip to Main Content
Learning JavaScript Design Patterns, 2nd Edition
book

Learning JavaScript Design Patterns, 2nd Edition

by Addy Osmani
April 2023
Intermediate to advanced content levelIntermediate to advanced
298 pages
6h 44m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning JavaScript Design Patterns, 2nd Edition

Chapter 11. Namespacing Patterns

In this chapter, we will explore patterns for namespacing in JavaScript. Namespaces can be considered a logical grouping of code units under a unique identifier. You can reference the identifier in many namespaces, and each identifier can contain a hierarchy of nested (or sub) namespaces.

In application development, we employ namespaces for many important reasons. JavaScript namespaces help us avoid collisions with other objects or variables in the global namespace. They’re also handy for helping organize blocks of functionality in a codebase so that it can be more easily referenced and used.

Namespacing any serious script or application is critical because it’s crucial to safeguard our code from breaking in the event of another script on the page using the same variable or method names we are. With the number of third-party tags regularly injected into pages, this can be a common problem we all need to tackle at some point in our careers. As a well-behaved “citizen” of the global namespace, it’s also imperative that we try our best not to prevent other developers’ scripts from executing due to the same issues.

While JavaScript doesn’t have built-in support for namespaces like other languages, it does have objects and closures that you can use to achieve a similar effect.

Namespacing Fundamentals

You can find namespaces in almost any serious JavaScript application. Unless we’re working with a simple code snippet, we must do our best to ensure ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern JavaScript From The Beginning

Modern JavaScript From The Beginning

Brad Traversy
Node.js Design Patterns - Third Edition

Node.js Design Patterns - Third Edition

Mario Casciaro, Luciano Mammino

Publisher Resources

ISBN: 9781098139865Errata PageSupplemental Content