Very first let us understand that why we need Namespaces in JavaScript. In JavaScript scope of a variable is in two flavours
- Global if defined outside any function
- Local to function and all nested function , if defined in function
So if a variable is not defined inside a function then its scope is throughout JavaScript program. This could cause problem if you want to use a JavaScript program in other JavaScript program or may be across webpages. There is no way in JavaScript scope of variable can be restricted to a block of code.
This can be achieved by using Function as Namespace in JavaScript. Essentially to create JavaScript Namespace, You need to put all codes of JavaScript program inside a JavaScript function.
Namespace can be created as following,
You see that to create namespace you need to start parenthesis and then put a function inside that as shown in above image. Now every variable you define under this function will have scope in this block of code only.
The other way you can create Namespace as given below,
Essentially a Namespace can be created in JavaScript as follows
<script type="text/javascript" >
var MyModule = {
//code for module here
GetData: function() {
var student =
{
name: "dj",
grade: 10
};
var nameisobjectofstudent = "toString" in student;
alert(nameisobjectofstudent);
}
};
</script>
And you can execute GetData() function as follows ,
In this way you can work with Namespace in JavaScript. I hope you find this post useful. Thanks for reading.

Pingback: Blog Posts of the Week (14th - 20th July 2013) - The South Asia MVP Blog - Site Home - TechNet Blogs