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
Recommended Posts:
- How to prevent overriding using fake namespace in JavaScript ?
- PHP | Namespace
- How to use :: Namespace Alias Qualifier in C#
- jQuery | event.namespace Property
- Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript
- How to compare two JavaScript array objects using jQuery/JavaScript ?
- JavaScript Course | Understanding Code Structure in JavaScript
- JavaScript Course | Conditional Operator in JavaScript
- JavaScript Course | Logical Operators in JavaScript
- JavaScript Course | Printing Hello World in JavaScript
- JavaScript Course | Data Types in JavaScript
- JavaScript Course | JavaScript Prompt Example
- JavaScript Course | Operators in JavaScript
- JavaScript Course | Loops in JavaScript
- JavaScript Course | Functions in JavaScript
- JavaScript Course | Variables in JavaScript
- JavaScript Course | Objects in JavaScript
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- How to include a JavaScript file in another JavaScript file ?
- JavaScript | Let
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.

