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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Car started
Bike started

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.