JavaScript tip 3: Namespaces

To avoid collisions, declarations overwriting each other and such, we can use JavaScript to create namespaces.

While not supported directly by the language the pattern is pretty common.

First let’s imagine we are including two separate JS files which both include a function named customRounding.

// first included file
var customRounding = function(number) {
  return number.toFixed(2);
}

// second included file
var customRounding = function(num) {
  return num.toFixed(3);
}

In our index.html we are calling this function:

console.log(customRounding(1.23456));

The problem is that the second file will have overwritten the declaration in the first file. To prevent such a collision, it is advisable to use a namespace likewise:

// first included file
var NS1 = {
  customRounding: function(number) {
    return number.toFixed(2);
  }
};

// second included file
var NS2 = {
  customRounding: function(num) {
    return num.toFixed(3);
  }  
};

// in our index.html file
console.log(NS1.customRounding(1.23456));

We can also use this pattern to make some variables and functions private by converting our namespace to an IIFE and then declaring the private members as variables and returning our public members:

var NS1 = (function() {
  // private stuff
  var aPrivateVar = 42;
  var aPrivateFunction = function(number) {
    alert('Hi!');
  };

  // public stuff
  return  {
    customRounding: function(number) {
      return number.toFixed(2);
    }  
  };  
})();

 

 

JavaScript tip 2: Function factories using closures

Here’s how we can use closures to build “function factories”:

var addElement = function(destination) {
  return function(element) {
    document.getElementById(destination)
            .appendChild(element);
  }
};

var addElementToMain = addElement("main");
var addElementToAlternate = addElement("alternate");

var p = document.createElement("p");
p.appendChild(document.createTextNode("Vanilla JS"));

addElementToMain(p);

You can also check out and run this example as a CodePen here.

In this example, addElement is a function which will return a new function with the destination parameter closed. This way we can create functions to add child elements to various parent elements.

The addElementToMain and addElementToAlternate are two functions created this way.

JavaScript tip 1: Function Expressions

If you are creating your JavaScript functions using Function Declarations, a good tip is to switch to Function Expressions.

First here is an example of a Function Declaration:

function declared() {
  console.log("First declared function.");
}

Sadly because of variable hoisting, which means that declarations are hoisted to the top of their scope in JavaScript, we can run into some problems likewise:

function declared() {
  console.log("First declared function.");
}

declared();

function declared() {
  console.log("Overwriting declared function.");
}

In this case since both Function Declarations are hoisted to the top we end up with “Overwriting declared function.” being logged out to the console.

Here’s what the code looks like after hoisting:

function declared() {
  console.log("First declared function.");
}

function declared() {
  console.log("Overwriting declared function.");
}

declared();

Function Expressions provide another way to create a function and avoid this kind of problem. Here’s the previous example using Function Expressions:

var expression = function() {
  console.log("First Function Expression.");
};

expression();

var expression = function() {
  console.log("Not gonna happen!");
};

Which this time is returning “First Function Expression.”. While both expression variable declarations are hoisted up, their definitions aren’t.

Here’s this last example after hoisting:

var expression = undefined;
var expression = undefined;

expression = function() {
  console.log("First Function Expression.");
};

expression();

expression = function() {
  console.log("Not gonna happen!");
};

It’s thus safer to use Function Expressions over Function Declarations.

I decided to learn JavaScript, again…

My first experience with JavaScript was similar to many people. I was in high school and my programming experience was extremely limited. I had a personal Web page and ended up copy-pasting and modifying some existing JavaScript code I had found on the web.

I never even bothered to read any tutorials or books on the language, but there was plenty of code to be found on the internet and JavaScript is really easy to get into. Which surprisingly, might be JavaScript’s biggest problem.

JavaScript’s problem

Fast forward years later, I learned more along the way but I never gave the language the treatment it deserved, the treatment I gave other languages.

Regarding JavaScript, non-programmers can get by without having to learn programming and developers can get by never having to invest time learning JavaScript.

While I was discussing this subject with a good friend and colleague of mine, he confided that he had zero experience with JavaScript prior to his current job and that he never took time to learn any of it. Nonetheless, he was still able to accomplish what was needed for our ASP.NET MVC project.

It took about 2 or 3 years into my professional career to learn that JavaScript was a Prototype based language and what that meant. Years later when I read about how companies were having trouble recruiting qualified JavaScript engineers it made me think about the general lack of focus on JavaScript.

I have often heard or read complaints that there is a lot of horrible JavaScript code floating around the Web or that JavaScript is just plain bad. I think a lot of this has to do with JavaScript’s low barrier to entry and the fact that a lot of people treat it as a second-class citizen of programming languages.

Sure, as a language it’s simpler than others but it’s also becoming more and more prevalent with many people talking of a JavaScript renaissance and many new cool projects appearing on the Web.

My plan

When I learn a programming language I set aside time to properly learn it. I start out by going through a good internet resource or book. I check blogs and try to find the best ones.

I try to really learn how to do things idiomatically in the language.

Ruby programmers will speak about something being done in a Rubyish way, Python programmers will talk about something being Pythonic. This is what I mean by idiomatically, writing code how it is suppose to be written in a language.

So I have decided to wipe the slate clean. I am starting over and will embrace JavaScript and really try grok it. I will treat it like I treated Ruby, Python or Erlang.

I have ordered JavaScript the Good Parts, I will read the JavaScript Guide and check the JavaScript Reference on the Mozilla Developer Network. I will also check some resources on JavaScript patterns and maybe have a look at the source of some JS libraries like Underscore.js.

If you’re using JavaScript and like many people never took the time to really master it, why not start over again?