Give a Hoot, Don’t Pollute…The Javascript Global Namespace

by | General

In software programming, I find that just when you think you’ve mastered a particular concept or programming language, you get bonked over the head by a new concept or idea that may have previously blindsided you.

I’ve blogged recently about the rising importance of Javascript as the future of software development.

The evidence is inescapable when you observe how many new javascript based frameworks seem to be coming out, seemingly every day.

With the advent of NodeJS, you can now develop a full stack software application across all three major tiers, the UI, the business layer and the data layer, in javascript. This technology stack is often referred to as the MEAN stack.

Javascript innovation is moving so fast it’s literally making my head spin. All you have to do is google the latest in Javascript trends and you’ll quickly notice EVERYONE seems to be jumping on the Javascript bandwagon.

There are two major camps of software developers programming in Javascript.

The younger developers who started their programming careers on the Javascript/MEAN stack. They have the fortunate timing of riding the current wave of Javascript development, knowing their knowledge and experience will carry them forward comfortably for the foreseeable future for their career.

Then there are the software developers like myself, who originally come from other technology stacks. In my case, my professional software career was built on top of the Microsoft stack, starting out in Visual Basic, and moving up to .NET and the C# programming language.

Of course, there are tons of other programming tech stacks other than Microsoft … the LAMP stack, Java stack, Ruby on Rails, Python, iOS, Android, the list goes on and on.

This is only conjecture on my part, but I’m guessing at least some of the developers like myself, who come from other tech stacks like .NET, etc, are going through a bit of struggle adjusting to the new reality that Javascript is the wave of the future of programming.

Don’t get me wrong.

I LOVE the process of learning new things. It’s part of the appeal of being in software development … nothing ever stays the same, and there’s always something new to learn just around the corner.

But at the same time, there’s the human nature aspect to consider. We all have our personal comfort zones. When I first started out in my programming career, Microsoft was truly the king of software development. Developers who jumped on the Microsoft programming bandwagon around the same time as myself, were likely rewarded with HUGE interest from IT departments across the country.

Make no mistake … Microsoft is still a huge force in the software development world. But they’re certainly not the only major player in town.

Especially with the rise of the internet. Giants like Google, Facebook, Amazon, Apple and others are making their own waves and creating new fortunes off internet technology.

The world has moved on and developers who don’t keep with the times, risk the danger of losing their job marketability.

That said, forcing yourself to get out of your comfort zone and learn new tech stacks and languages like Javascript isn’t necessarily a walk in the park.

Sure, if you’ve learned one computer language, you can pretty much pick up a new one without too much struggle. After all, all programming languages possess the same basic concepts.

Things like if-then branching logic. Loops. Data structures and variables.

Still, there are subtle nuances that can take time for a developer to truly grasp.

For myself, the basic Javascript language syntax was relatively easy to pick up … the syntax is based on the C programming language, and anyone familiar with C, C++, Java or C# shouldn’t have any problem picking up the core Javascript concepts.

It was more a particular concept about Javascript that I’ve only recently learned about, that was quite surprising to discover.

JAVASCRIPT HAS A PROBLEM WITH ENCAPSULATION.

In the world of Javascript, it’s often referred to as “polluting the global namespace”.

To better understand what global namespace problem is about, you need to understand what encapsulation is.

Back in the bad old days of software programming, many computer languages didn’t have the concept of encapsulation.

If you declared a variable called ‘foo’ somewhere in your code, then pretty much any other code in your program could access the variable ‘foo’, and worse yet, modify the value unintentionally.

This is bad, because it makes tracking down software defects and bugs a herculean challenge because you must literally scan and examine the entire source code base to be sure something isn’t inadvertently modifying that variable.

So what, if it’s a small program, you might say … it’s just a few extra minutes, at most, of additional effort.

Ok, so what if it isn’t a small program? Say you’re a core Microsoft Windows operating system programmer.

The last time I checked, it’s somewhere north of fifty million lines of code.

Imagine if all functions and variables were global in scope, meaning that any other place in the code could access it.

Now imagine that one of your variables was changing values when you’re positively sure it shouldn’t.

You have no idea what’s changing your variable. So now you’d be forced to start hunting through fifty million lines of code to figure out where the variable is getting set when it shouldn’t … hope you don’t have vacations planned for a couple decades!

The concept of “encapsulation” is all about information hiding. It’s a way of making sure the data and functions in your application are only visible to the other places in your code that need it.

The military does that all the time when they classify documents as “top secret”. Only authorized personnel can have access to top secret materials. Unauthorized personnel are not allowed anywhere near top secret classified materials.

In modern programming languages like Java, C++ and C#, you can specify the “top secret” access level of functions and variables.

The two primary access categories are ‘private’ and ‘public’.

You can declare data variables as private inside of a function.

ie.
string DisplayFullName() {
private string firstName = “John”;
private string lastName = “Kim”;

return firstName + ” ” + lastName;
}

Inside the DisplayFullName() method, we’ve declared two data variables to represent a first name and last name. The key to note is they are bothd declared as private scope.

It means that no other code outside the DisplayFullName() function can access or modify those variables.

Only the code INSIDE the DisplayFullName() method may access and modify those variables. The function takes those two privately declared variables, concatenates them together to build a full name value, and return it as a new string, which the function returns as it’s return type.

Imagine what would happen if firstName and lastName were declared as public scope. That would mean that any other code outside the DisplayFullName() function could inadvertently change either of those variables.

You would discover that the function returns a full name value that is completely different from the expected value of “John Kim”. You’d have to start digging through all other places in the source code to figure out what might have changed either of those variables.

That is essentially what encapsulation is all about. It helps make your code easier to maintain and debug.

Unfortunately Javascript doesn’t have a native mechanism like the keywords ‘private’ and ‘public’ to change the access level of functions and variables.

Every variable and function declared in Javascript becomes part of a global object commonly referred to as the “global namespace”.

This can be a potentially huge problem for the very reason we just discussed.

Say your Javascript uses external third party libraries, which in fact, is very common in web development. Libraries like JQuery, Bootstrap and Underscore are commonly used in modern day Javascript applications.

By default, any function or variable contained in these libraries all belong to a global namespace object.

Imagine if you have a variable declared as ‘foo’ in both the JQuery and Bootstrap libraries. You could end up with the same data collisions we described before.

Up until recently, I had no idea about the global namespace … or I may have heard about the concept at one time, but I never really paid attention to it.

But as I began working more with Javascript, I realized I couldn’t continue ignoring this problem.

Encapsulation in software development is a major requirement for best practices.

Ignoring encapsulation risks introducing bad flaws and major defects into your code.

Fortunately Javascript has other mechanisms besides declaring things as private scope.

They may not be as straightforward, but they accomplish the same end goal of encapsulation.

There is a construct in Javascript called the “immediately invoked function expression” or “iffy” for short, which Javascript programmers often use to avoid “polluting” the global namespace and the problems associated with it.

// this is an Immediately Invoked Function Expression
(function() {
// any variables or functions defined inside here stay hidden from
// the global namespace or any other functions defined outside of here

var x = 1; // x is private and not accessible or visible outside of the IIFE

// this function is only visible inside this IIFE
function doStuff() {
// ..code
}
})();

It may look strange, but any variables or functions declared inside of the Immediately Invoked Function Expression stay private and invisible from anything defined outside of it, including the global namespace object.

Putting your Javascript code inside IIFEs will greatly reduce the chances that any of your defined variables and functions will conflict with third party libraries that may coincidentally share the same variable and function names.

In Ecmascript 6 (aka Ecmascript 2015), the ‘let’ and ‘const’ keywords have been introduced to allow for simpler and more straightforward enforcement of data encapsulation.

function someFunction()
{
let count = 10;
}

console.log(count); // causes an undefined reference error because count is not visible outside the function definition, someFunction()

Unfortunately, ES6 is still not fully supported across all major browsers, so it will take time before widespread adoption of the ES6 spec.

Until then, one can use the IIFE construct to enforce encapsulation among older browsers.

Programming languages and concepts will always evolve, but timeless principles like encapsulation will always remain valid. As a developer, it’s always important to keep timeless principles in mind, even when you’re tackling and learning new technology.

So remember folks, give a hoot, don’t pollute….the global namespace!

Ready for Your Next Job?

We can help! Send us your resume today.


Need Talent?

Submit your job order in seconds.


About ProFocus

ProFocus is an IT staffing and consulting company. We strive to connect a select few of the right technology professionals to the right jobs.

We get to know our clients and candidates in detail and only carefully introduce a small number of candidates that fit the role well.