Friday, September 5, 2025
HomeLanguagesJavascriptJavaScript | Namespace

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 isolate these contexts such that the same identifier can be used in different namespaces. In this article, we will discuss how namespaces can be initialized and used in JavaScript. JavaScript does not provide namespace by default. However, we can replicate this functionality by making a global object which can contain all functions and variables.

Syntax:

  • To initialise an empty namespace
     var <namespace> = {}; 
  • To access variables in the namespace
     <namespace>.<identifier> 

Below example illustrates the namespace in JavaScript:

Example: As shown below, the identifier startEngine is used to denote different functions in car and bike objects. In this manner, we can use the same identifier in different namespaces by attaching it to different global objects.




<script>
var car = {
    startEngine: function () {
        console.log("Car started");             
    }        
}
  
var bike = {
    startEngine: function () {
        console.log("Bike started");
    }
}
  
car.startEngine();
bike.startEngine();
</script>


Output:

Car started
Bike started
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6750 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS