26
OctDefining Namespace or Nested Objects in JavaScript
JavaScript is a dynamic language. You can create objects on the fly, and objects can contain other objects, also it does not support the concept of namespace like C#.
Basically, a namespace is like a container which contains classes. In JavaScript you can achieve the same functionality as Namespace by creating nested objects. And since window itself is an object you can actually create objects directly into it. But if we would like to create an object in a non-existent nested namespace, we'll need to create that first. To gain a deeper understanding of namespaces and other JavaScript concepts, you can enroll in a Free JavaScript Course With Certificate. This course will provide you with practical insights into JavaScript namespaces, object manipulation, and much more.
Read More: 50+ Javascript Interview Questions
Simple Namespace<script> var MyNameSpace = { calculateVat: function (base) { return base * 1.21; }, product: function (price) { this.price = price; this.getPrice = function () { return this.price; }; }, doCalculations: function () { var p = new MyNameSpace.product(100); alert(this.calculateVat(p.getPrice())); } } //instancing product class var p = new MyNameSpace.product(150); //calling product class method alert(p.getPrice()); </script>
Read More: Javascript Developer Salary in India
Namespaces Nesting
<script> var MyNameSpace = { calculateVat: function (base) { return base * 1.21; }, MyNameSpace2: { product: function (price) { this.price = price; this.getPrice = function () { return this.price; }; } }, doCalculations: function () { var p = new MyNameSpace.product(100); alert(this.calculateVat(p.getPrice())); } } //instancing product class var p = new MyNameSpace.MyNameSpace2.product(150); //calling product class method alert(p.getPrice()); </script>
Conclusion
Namespaces in JavaScript are a way to organize code and avoid naming conflicts by encapsulating variables, functions, and objects under a unique identifier. They help make large codebases more maintainable, modular, and readable, especially when multiple scripts or libraries are used together.
Angular drives apps like PayPal and Upwork. Don’t miss your chance—join our Angular JS Online Course and build world-class projects now!
Take our Javascript skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.