Namespacing in JavaScript

Sure, JavaScript can create some amazing formatting on the fly through on-clicks and on-loads. It makes interactivity between the web user and website both breathtaking and useful. But JavaScript suddenly becomes quite complex when it can do so much. While it is not only regarded as a “loosely typed language” – yes, it actually makes variables without the type being defined, it also does something even more quirky – all variables are actually global too. And when the same variables (or objects) start being used all at once – intentionally or unintentionally – code can start getting garbled and confusing and maybe even stop working, especially if something clashes. This is called polluting the global namespace when that happens.

(A more simplified example would be how in school classroom, perhaps one might find two students have the same first name. How does one distinguish one from the other if the teacher wishes to acknowledge only one of them? How will each student know who is being called on? They can’t. The same problem can happen with programming.)

Namespacing is the technique of keeping everything separate, or rather perhaps better put: contained. So while the designer’s interactive changes found in a website (simple things like color displays) can happen with different unique ID tags labeled as variables in JavaScript, namespacing covers far more serious programming territory for back-end developers, involving holding everything else together.

Functions Signify Scope (aka “my home is your home”)

Imagine that you have just moved into a new house and this weird outgoing person suddenly spots you in the front yard, introducing herself as your neighbor. She gives you massively big hug, drags you into her house by pulling your arm, forcing you have a cup of her coffee and have some of her cake. She goes on to assure you, “If you need anything at all, just come by – any time! My home is your home.” You go on to nod and smile and wonder how anyone can be so open to visitors seeing you just met them. Oh well, they seem nice enough.

This is how JS also operates…

In JavaScript, functions are not walled fortresses where variables are safe from outside influences. This is not your typical programming rule! It required so much brain bending for me to accept that.

I actually finally started to understand how this could be possible when I learned how “this” works. “This” is a special word used for objects in JavaScript that points immediately one level up within that object being declared. Why? It just does. It’s useful.  It makes sense if you need to use it. Sometimes you might have a program that needs to backtrack its own steps. It’s not too different to when one is making conversation and what you just literally just talked about is also specifically referred to as: “THIS”. It is exactly the same concept. Anyway, going back to namespaces…

Ultimately, “this” (in programming) literally points one level up from where you have your current line of programming code. Applying this reasoning, everything one level up from any function used in an HTML page, will incidentally automatically be the window object where the HTML resides. And yes, that means in a way, that the whole thing is one giant object! So to go one level up from a variable in a function can in theory mean you are in the global scope of that one big “function” (think “also object” – they are the same thing in this case) is therefore accessible EVERYWHERE – even in other functions you might choose make. They really are just like very close neighbors – perhaps even uncomfortably close.

How This Relates to Namespacing

Going back to the neighbor analogy, it is best not to shrug off the neighbor as merely  being just nice enough. Who knows, she might start even barging into your home next time with the same degree of openness under the guise of friendship:

“As a well-behaved ‘citizen’ of the global namespace, it’s also imperative that you do your best to similarly not prevent other developer’s scripts executing due to the same issues.” – Addy Osmani’s post entitled, Essential JavaScript Namespacing Patterns.

Your home is their home and their home is your home! Things also get complicated when sharing happens. In a work environment, people will of course almost always work together to code. They will share code to break down the workload and break down complex tasks into simpler ones:

“In any modern day application, Namespace is a must to have because at the end, we need third party libraries and components.” – Code Project

Perhaps the most widely used example of a third party library for JavaScript would be JQuery. And yes, that of course also uses its own sets of variables and objects, separated by namespaces.

Namespacing in Action

SETUP

Now it’s time to see an actual example of namespacing. This example is meant to be very hands-on. Feel free to try it yourself. Four files are be used: one is the main file, two other files contain blocks of JavaScript, and the third one is a separate file meant to run the JavaScript code.

Imagine you have a main file called index.html:

 namespacing1

Imagine you have a file called announcement1.js

 namespacing2

Imagine you have another file called announcement2.js

 namespacing3

Imagine you have a third file that calls for all the action

 namespacing4

RUNNING THE PROGRAM

PROBLEM! This will not work as expected! Instead of displaying “President” on one line and “VicePresident” on another, it will print the second variable twice. While the functions have different names the variable name was the same (in the global scope) and was overridden.

 namespacing5

HOW TO FIX!

Create separate objects with properties as a work-around. Change announcement1.js to be as follows:

 namespacing6

Change announcement2.js to be as follows:

 namespacing7

Change the third file that calls for all the action

 namespacing8

SOLUTION!

This should now work as expected! It will print:

namespacing9

Real-Life Example

All things mean much more when applied in an actual setting where you can see the code in action. Here is some example code from CodeProject before it was made namespace-friendly:

namespacing10

(screenshot taken from Code Project’s article entitled: JavaScript Namespace)

It looks like your typical program, right? And here is that same code made so that it is namespaced:

namespacing11

(screenshot taken from Code Project’s article entitled: JavaScript Namespace)

Can you see the difference? The sections of code are now lumped together as one big chunk now: a global object called MYAPPLICATION and “To access any of the methods or variables, you need to fetch it through the MYAPPLICATION.”

namespacing12

(screenshot taken from Code Project’s article entitled: JavaScript Namespace)

It clearly takes some more work to make something namespace-friendly, but as Code Project points out, these three global items, calculateTax, product, doTaxCalculations “will really put us in trouble if we are using 3rd party libraries and they also contain the same name. Like if it is used before other library, it will be overridden by Library and vice versa.” In this case, record keeping and handling data for sales are involved, and one cannot help but imagine can potentially create serious problems if the money matters are not computed correctly.

Namespacing Tools

Efforts have of course been made to make namespacing easier. Ever heard of Angular JS or React? Those are some of the latest ways to get JavaScript better organized and in the form of a framework that uses it’s own namespace.

In thanpolas tech blog, it is pointed out that medium to large scale web applications are so complex that they have to use namespacing for Javascript. This is understandably so. Try to make sense of this screenshot below taken from a browser console! Perhaps even more intimidating is to realize that the it has already been made “easier” by being organized with drop down arrows because the browser recognized which parts of the JavaScript were made into namespaces and realize this is only part of an even bigger chunk of programming code:

namespacing13

(Screenshot taken from thanpolas post entitled, Development Using Namespaces)

Conclusion

Namespacing matters a lot! It should be evident now why JavaScript is a must-learn programming language from a back-end perspective. Namespacing adds safety to programming code so that it won’t break. Namespacing reveals a whole side of web development that involves a lot more than just using JavaScript for designing interactive visual design aspects for a web page.

 

Advertisements

About Juliette

Techy girl who also loves both technology and culinary arts. Programming and recipes are my thing! Currently learning about web development while taking a bite out of a delicious crusty piece of bread.

4 thoughts on “Namespacing in JavaScript

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s