Better use of Memoization JavaScript

Referring to the post Generating Unique Strings (Ids) in JavaScript where we looked at how to generate unique strings in JavaScript. Also I mentioned the performance and memory issues with the approach.

So, here we are going to look a much better use or application of Memoization, but we won’t be using it for generating unique strings. We will be looking at another issue and will try to find an efficient way to handle it.

We all know that accessing DOM elements is pretty much costly in terms of performance. Lets look at an example of such an issue.

    function someFunction() {
        var text = document.getElementById("some-id").innerHTML;
        return text;

Now suppose the above function is executed several times(reason could be anything like, user clicks). Every time this function is executed, it traverses the DOM and then returns it, which makes it really inefficient.
Now, I hope we have the idea of how to solve problem. Exactly, we will simply access the element one time and store it in a cache rather than looking into the DOM again and again.
So, here is how to do it:

    function someFunction() {
        if(someFunction.cachedElement) {
            return someFunction.cachedElement.innerHTML;
        } else {
            var ele = document.getElementById("some-id");
            someFunction.cachedElement = ele;
            return ele.innerHTML;

This technique can be more efficient if we are looking for multiple elements for example by className of the elements. In that case, we just need to get all the elements only once and store them in an array. So next time when the function is called all the elements are returned from the cache rather than going through whole DOM.
Pretty fast haan, isn’t it!

Generating Unique Strings (Ids) in JavaScript

Well, there are tools in JavaScript that allow you to create unique ids or strings.

I will be using to two ideas to create these unique strings.

Method 1: Memoization

The idea is to generate some random string and checking if it has already been generated the recursively generate another one and test again. If the generated string has not been already generated, then simply cache it somewhere and return it to the calling function.

Here is an example of it:

function getUniqueId() {
    getUniqueId.cache = getUniqueId.cache ? getUniqueId.cache : [];
    var randomString = "ID" + Math.random().toString().substr(2);
    if(getUniqueId.cache.indexOf(randomString) === -1) {
        return randomString;
    } else {
        return getUniqueId();

Method 2: Closure
Closures are on of the coolest things available in JavaScript. Closures allow us to access local variables of a function when you are out of he scope of the function.
Doesn’t it sound a little crazy: “How can a local variable of a function can be accessed while we are not in the scope of that function i.e., the variable is out of the current scope!”.

Well its true that we cannot access the out of the scope variable of a function, But the variables and functions local to that variable can access it right. This is the concept we will be using to generate our unique Id or string.

Here it is.

    var getUniqueId = (function () {
        var local = 0;
        return function () {
            return local++;

In the function above we are returning a reference to a local function, for which the variable local is in the scope and can still increment it. So every time we call the getUniqueId function actually the inner function also gets called and every time we get the incremented value.

Issues with these approaches:

Both of the above concepts are pretty cool to use, but you know nothing comes for free. Both have some performance and memory(space) issues with them.

If we carefully analyze the situation when we use closures, we are accessing an out of scope function and we all know that accessing out of scope variables is much costlier as compared to accessing local variables and functions in terms of performance as JavaScript engine has to search for the variable which is sitting far-far away from the current scope.
The situations worsens if the function has been defined in the global scope, because we have to go all the way to the global scope to get it.

Now if we take a look at the Memoization approach, we will see as the list of cached items increases, the function will tend to slow down. This slowness is because of the fact that before returning the the generated string, it has to traverse the whole cache. This slowness increases as the size of the cache grows.

There are some memory issues too with theses approaches because we in case of Memoization are maintaining a cache and in case of Closure the JS engine has to preserve a whole scope and its members.

So using these tool with care is necessary or our program would run into other issues.

PS: Lets get lazy a bit
Now here is the laziest(and easiest) way to generate unique strings:

function getUniqueId(padding) {
   return padding + (new Date()).getTime();

I hope this last function is very self explainatory.

Two Dimensional Arrays in JavaScript

JavaScript does not provide any direct notion of creating multi dimensional arrays as provided by languages like, C and Java. But there are ways to solve this problem and create a multi dimensional array.
Below we are trying to create a two dimensional array. The idea is simple and can be applied to create arrays with more than two dimensions:

function init2DArray(
    var twoDArray;
    var cols = 10, rows = 15;
    var indexI;
    twoDArray = new Array(cols);
    for (indexI = 0; indexI < cols; indexI += 1) {
        twoDArray[indexI] = new Array(rows);
        for( indexJ = 0; indexJ < rows; indexJ += 1) {
            twoDArray[indexI][indexJ] = 0;

Now since we have got the 2D array, we may want to initialize it with something (may be with a default value).
Simply add the add the following code in the for loop after the first line:

for( indexJ = 0; indexJ < rows; indexJ += 1) {
    twoDArray[indexI][indexJ] = 0;

I have tried to make the code above error free but if anly problem persists, please post it in the comments. Also please feel free to suggest any optimization in the code.

The College on Mountains-GBPEC

GBPEC (Pauri) – Thats what we or should I say “everyone” calls it.

Thats Where I Lived and Learned


I don’t need to say how one would feel if one studies at this place, the picture says it all.
I (probable most of the college students) still don’t know the person who captured this amazing scene.

Other than this amazing weather I tried to list some of the small but really pretty nice things that make my college awesome.
Here are they:

  • The Campus Shop: You can get almost everything you need for a hostel life: stationary, ice-creams(in super chilled weather), and two of the most important things buckets room heaters
    The best memories I can re-collect from this campus shop are “being called and interrogated by the seniors” and “college girls in their cool casuals
  • The Post Office: This is probably the mean of getting money sending application forms and getting money. Some times we also got Ubuntu CDs which we ordered on-line absolutely free of cost.
  • The Anand Valley: This was the place of breakups and makeups and new love birds of the college and a party place for decent guys. The Magi and the Mutter Paneer I still can’t forget.
  • The Temple: This was probably on the highest peak in the college. First year boys cleaning it(seniors used to make only us do this) and girls preparing and decorating it. Boys come to this temple to get a glimpse of their crushes. The night long Janmashtmi Pooja everyone loved it.
  • Durga Restaurant: This is the place right in the beginning of the way from main road to college. Parties, night long pool games with seniors and friends was amazing. This is the place I came to know most of my seniors.
  • and Auditorium (best known as Audi): The first place of getting started: orientation, seniors, teachers, new unknowns(became friends later), celebrations, dance, acting, love proposals, rejections, flirts too etc. etc. almost everything starts here.

Here is another amazing view of the college captured on the same day as the one above:

Another amazing view

Simply saying an amazingly crafted place to spend your life.

Those days have passed but memories you can’t avoid them, sorry who wants to avoid them!

Best Resources For Web Developers and Learners

As a Web Developer I have come across some of the best online resources(blogs and websites from very good developers and Organizations) for Self Learners and Enthusiasts about web development.
The list starts here:

1.) John Resig: You definitely don’t want to miss his book Secrets of the JS Ninja

2.) MDN: Every thing for a web developer’s needs and demos(My personal favorite)

3.) Quirks Mode: Cross browser and compatibility issues

4.) Ben Nadel: For Latest web technologies AngularJS

5.) Digital Inspiration: How to guides and Tutorials

6.) Position-Absolute: Latest Web related technologies

7.) Cango Js: Amazing Library for creating interactive 2D and 3D objects in HTML5 Canvas

8.) KineticJS: Another amazing framework/library for interactive Canvas objects

9.) HTML5Test: Check you browser support for latest HTML5 features

There is something for everyone’s taste and interest in this list. Hope you all like it.