Namespace in JavaScript
Namespacing solves naming collision in programming. In javascript, there is no namespacing by default. But we can create one
What is a Namespace and Why we need a Namespace?
Whatever we write in javascript is the properties of the global window object. Sometimes we need to use the same identifier(variable, function) multiple times. But, due to scope problems naming collision occurs.
The namespace provides scopes to identifiers to avoid naming collision between them. We use the same variable in different contexts. Using namespace helps us to use the same variable in different namespaces.
Suppose we want to use two functions with the same name. But doing so creates an error
So, to escape error we will use a namespace through which we can use these two function easily without any error
How do we create a Namespace?
We normally create one global object which contains all variables, functions as properties of the object. It help’s us in a way that it doesn’t pollute the global environment.
Example of Namespace
Look at the code above. We used the eat and sleep function in both men and women object. Here these function doesn’t collapse with one another.
2 eat function + 2 sleep function = 4 functions in total inside two global object. In this way, we can nest hundreds of variables and function inside one global object.
Using namespace we created two sleep functions and they are working without any error.
Keep in mind that these functions aren’t accessible outside of the object. This won’t work.
sleep();
eat();
That is why we can use this namespacing method to hide our code.
There are some other ways to hide code. Let’s look at these methods.
Ways to hide code
1st method: Wrap the code inside curly braces. You must use let/const to declare variables and functions.
2nd method: Wrap with function with “()” and then call the function with “()” at the end.
It doesn’t matter you used const/var/let to declare variables or functions. All variables and functions will be inaccessible from the outside
Thank you so much for reading my article