JavaScript functions as Namespaces

Very first let us understand that why we need Namespaces in JavaScript. In JavaScript scope of a variable is in two flavours

  1. Global if defined outside any function
  2. 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;


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.

One thought on “JavaScript functions as Namespaces

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s