Advanced Concepts

Defining Namespace or Nested Objects in JavaScript

What is a Namespace in JavaScript?

Since JavaScript doesn't have built-in namespaces like some languages, developers use nested objects to group related variables and functions and avoid naming collisions in the global scope.

Example

let MyApp = {};

MyApp.utils = {
    formatDate: function(date) {
        return date.toDateString();
    }
};

MyApp.models = {
    user: { name: "Alice", age: 25 }
};

console.log(MyApp.models.user.name); // "Alice"

Why Use Namespacing?

  • Prevents global variable name clashes between different scripts or libraries.
  • Organizes related functionality logically under a single object.
  • Common pattern before ES6 modules became widely supported.

Ready to master real-world JavaScript development?

Learn JavaScript hands-on with mentor-led, live sessions.

Explore Course