Open In App

JavaScript | Namespace

Last Updated : 22 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
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: 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.

javascript




let car = {
    startEngine: function () {
        console.log("Car started");            
    }        
}
 
let bike = {
    startEngine: function () {
        console.log("Bike started");
    }
}
 
car.startEngine();
bike.startEngine();


Output

Car started
Bike started

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads