Skip to content
Related Articles

Related Articles

Improve Article

JavaScript | Namespace

  • Difficulty Level : Basic
  • Last Updated : 21 Mar, 2020
Geek Week

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

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!

My Personal Notes arrow_drop_up
Recommended Articles
Page :