Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
String in DSA Using JavaScript
Next article icon

Namespacing in JavaScript

Last Updated : 06 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts. Using namespaces in such a scenario will isolate these contexts such that the same identifier can be used in different namespaces.

Syntax:

//  To initialize an empty namespace 
let <namespace> = {};
// To access variables in the namespace
<namespace>.<identifier>

Example: Here, MyApp is the namespace. MyApp.calculator and MyApp.logger are sub-namespaces or modules within the MyApp namespace. The add, subtract, and log functions are methods contained within their respective namespaces.

Javascript




// Creating a namespace called 'MyApp'
let MyApp = MyApp || {};
 
// Adding functionality to the namespace
MyApp.calculator = {
    add: function (a, b) {
        return a + b;
    },
    subtract: function (a, b) {
        return a - b;
    }
};
 
MyApp.logger = {
    log: function (message) {
        console.log(message);
    }
};
 
// Using the functionality from the namespace
var result = MyApp.calculator.add(5, 3);
MyApp.logger.log('Result: ' + result);
 
 
Output
Result: 8 

Here are some important points about namespacing in JavaScript:

  1. Preventing Global Scope Pollution: Namespacing helps prevent variables and functions from polluting the global scope. By encapsulating them within a namespace, you reduce the risk of naming conflicts with other scripts or libraries.
  2. Organization and Modularity: Namespacing promotes code organization and modularity. It allows you to group related functions and variables under a common namespace, making the codebase more structured and easier to manage.
  3. Encapsulation: Namespacing provides a level of encapsulation by restricting access to variables and functions within the namespace. This helps in avoiding unintended external interference and promotes information hiding.
  4. Readability and Maintenance: Code within a namespace is more readable and maintainable. Developers can easily understand the context of a particular piece of functionality by looking at its namespace, making it easier to navigate and update code.
  5. Reducing Naming Conflicts: In large projects or when integrating multiple libraries, naming conflicts can arise. Namespacing helps mitigate these conflicts by isolating code within its designated namespace.



Next Article
String in DSA Using JavaScript
author
ayushraghuwanshi80
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • JavaScript | Namespace
    Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts. Using namespaces in such a scenario will isola
    1 min read
  • How to declare namespace in JavaScript ?
    The coding standard of assigning scope to identifiers (names of types, functions, variables, and so on) to avoid conflicts between them is known as a namespace. It is a framework for a collection of identifiers, functions, and methods. It gives its contents a sense of direction so that they are easi
    3 min read
  • JavaScript find label
    Finding a label using JavaScript involves accessing form elements and their associated labels to enhance user interaction. In this article, we’ll explore methods to efficiently locate and manipulate labels, ensuring a seamless user experience on your web pages. What Role Do Labels Play in HTML Forms
    3 min read
  • Objects in Javascript
    An object in JavaScript is a data structure used to store related data collections. It stores data as key-value pairs, where each key is a unique identifier for the associated value. Objects are dynamic, which means the properties can be added, modified, or deleted at runtime. There are two primary
    4 min read
  • String in DSA Using JavaScript
    A string in JavaScript is a sequence of characters enclosed in single ('), double ("), or backticks (`). Strings in JavaScript are immutable, meaning their contents cannot be changed after creation. Any operation that modifies a string actually creates a new string. Example: [GFGTABS] JavaScript let
    2 min read
  • Shadowing Properties in JavaScript
    Shadowing properties in JavaScript refer to the scenario where a variable declared within a nested scope has the same name as a variable in its outer scope. This can lead to confusion and unexpected behaviour, as the inner variable may "shadow" the outer one, effectively hiding it from the outer sco
    2 min read
  • JavaScript Memoization
    As our systems mature and begin to do more complex calculations, the need for speed grows, and process optimization becomes a need. When we overlook this issue, we end up with applications that take a long time to run and demand a large number of system resources. In this article, we are going to lo
    6 min read
  • JavaScript String Formatting
    JavaScript string formatting refers to the technique of inserting variables, expressions, or values into strings to make them dynamic and readable. It can be done using methods like concatenation, template literals (backticks), and custom formatting functions, which help create flexible and clean st
    5 min read
  • JavaScript String concat() Method
    The concat() method in JavaScript join or concatenate two or more strings together. It does not change the existing strings and returns a new string. This method efficiently combines multiple strings into one, ensuring the original strings remain unchanged. Syntaxstr1.concat(str2, str3, str4,......,
    3 min read
  • JavaScript String Methods
    JavaScript strings are the sequence of characters. They are treated as Primitive data types. In JavaScript, strings are automatically converted to string objects when using string methods on them. This process is called auto-boxing. The following are methods that we can call on strings. slice() extr
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences