Event Delegation

First let’s create HTML of an unordered list (ul).
HTML

<ul id="todo-app">
	<li class="item">Item 1</li>
        <li class="item">Item 2</li>
        <li class="item">Item 3</li>
        <li class="item">Item 4</li>
</ul>

Event Delegation technique:

Suppose if you have attached the event listener click on li rather than on ul, then you are attaching the listener to every li element and if there are n number of li elements, this is not the efficient way to attach the event listeners. Rather attach the event listener to ul and call or target only specific li element as listener. This is called event delegation.

Wrong implementation:

document.addEventListener('DOMContentLoaded', function() {
  
  let app = document.getElementById('todo-app');
  let items = app.getElementsByClassName('item');
  
  // attach event listener to each item
  for (let item of items) {
    item.addEventListener('click', function() {
      console.log('Wrong: You clicked on item: ' + item.innerHTML);
    });
  }
  
});

Correct implementation:

document.addEventListener("DOMContentLoaded", function() {
  let app = document.getElementById("todo-app");
  
  app.addEventListener("click", function(e) {
    if(e.target && e.target.nodeName === "LI") {
      let item = e.target;
      console.log("Correct: You clicked on: " + item.innerHTML);
    }
  });
});



Check this codepen link for further understanding: Event Delegation

-By
Uma Maheswar
Helical IT Solution

Functions in JavaScript

Consider the given code below:

1:    function doSomething(a) {
2:        function doSomethingElse(a) {
3:            return a - 1;
4:        }
5:        var b;
6:        b = a + doSomethingElse( a * 2 );
7:        console.log( b * 3 );
8:    }

doSomething( 2 );

By considering above code, if you are learning JavaScript, you might get 9 as your answer. But think twice. Or let me explain you in a better way.

First you have to understand that JavaScript treats functions as its first class citizens. Meaning, JavaScript compiler will first compile functions.

Hence in the above code, let me breakdown into smaller segments and see what is happening where. So firstly we start at line 6 which says:

b = a + doSomethingElse( a * 2 );

Again narrow down line 6 and consider:

doSomethingElse( a * 2 );
// returns 4

Now the JavaScript compiler goes to line 2:

function doSomethingElse(a) {
    return a - 1;
}

// returns 3 because now a is 4 but not 2

And again compiler comes back to line 6 and re-compiles the code:

b = a + doSomethingElse( a * 2 );

Now b returns 5 because doSomethingElse( a * 2 ); is 3 now (which is returned from above function doSomethingElse)

Hence the result is 5 * 3 = 15.

As a beginner, it is recommended to understand what is happening at the background and visualize it before start coding actual code. Cheers..!! Happy Coding.

-By
Uma Maheswar
Helical IT Solution

JavaScript Timers

It is well known fact that JavaScript by nature is single-threaded which says that only one part of JavaScript code executes at a time. And interesting thing about timers is, they gets executed irrespective of other threads that are already in queue and also never interrupts another currently-running timer.

It is important for a complex JavaScript application not to become unresponsive to the user causing the browser to hang and eventually suspend all the updates of the page to be rendered while JavaScript is executing. It is therefore a fact that the complex operations should be managed in portions rather than a bulk.

Since JavaScript timers has the capability to suspend execution of a piece of code until a later time, this prevents the browsers from hanging. By considering this point, what we can do is to convert the bulk of code into loops and operate without blocking operations. Let’s consider an example to explain this:

<table>
    <tbody></tbody>
</table>

<script>
    var table = document.getElementsByTagName("tbody")[0];
        for ( var i = 0; i < 2000; i++ ) {
	    var tr = document.createElement("tr");
            for ( var t = 0; t < 6; t++ ) {
		var td = document.createElement("td");
  	        td.appendChild( document.createTextNode("" + t) );
  	        tr.appendChild( td );
            }
	table.appendChild( tr );
    }
</script>



In the above example,we are creating large amount of DOM nodes for populating a table with numbers. This is a expensive execution and will definitely allows the browser to hang. Now if we introduce timers into this situation to achieve a different, and perhaps a better solution to the above problem can be achieved. Check this code:

<table>
    <tbody></tbody>
</table>

<script>
    var table = document.getElementsByTagName("tbody")[0];
    var i =0, max = 1999;

    setTimeout(function() {
        for ( var step = i + 500; i < step; i++ ) {
            var tr = document.createElement("tr");
            for ( var t = 0; t < 6; t++ ) {
		var td = document.createElement("td");
  	        td.appendChild( document.createTextNode("" + t) );
  	        tr.appendChild( td );
            }
            table.appendChild( tr );
        }

        if(i < max) {
            setTimeout( arguments.callee, 0);
        }
    }, 0);
</script>



In the above modified example, what we have done is, we broke up our intense operation into smaller operations and each creates equal number of DOM nodes. Even if worst case is considered, operations will be further broken and increasing number of DOM nodes for each operation. It has to be noted that we don’t execute the above code in an infinite loop. Now the browser gets updated every once a while, not allowing the user to see these types of update that occur. But, it is important to remember that they occur.

In case of any doubt, please go through this video which explains how javascript timers work regarding setting setTimeout to 0.

JavaScript Event-Loop

-By
Uma Maheswar
Helical IT Solution

Primitive Wrapper Types in JS

In this post, I’m going to focus on basic concepts of JavaScript. So we are going to learn the concept of primitive wrapper types in JavaScript which is confusing to most.

So, there are three primitive wrapper types and they are: 1: String, 2: Number and 3: Boolean. And these primitive wrapper types are reference types that are automatically created behind the scenes whenever these primitive wrappers types are read. Let’s consider an example to explain our point.

var name = "Lorem";
var firstChar = name.charAt(0);
console.log(firstChar);     // "L"

In the first line of the above code, a primitive string value has been assigned to name. The second line treats name like an object and calls charAt(0) using dot notation.

Now let us examine behind the scenes of the above code:

// what the JavaScript engine does
var name = "Lorem";
vat temp = new String(name);
var firstChar = name.charAt(0);
temp = null;
console.log(firstChar);     // "L"

Since the second line in the above code uses a string (a primitive) like an object, the JavaScript engine creates an instance of Sting so that charAt(0) will work. The Sting object exists only for one statement before it’s destroyed (a process which is called autoboxing). At this point, since we have said that it is an object, we might consider to add a property to it. So let us give it a try:

var name = "Lorem";
name.last = "Ipsum";

console.log(name.last);     // undefined

The above code tries to add the property last to the string name. And looking at the code, it just looks fine but wait, What happened? Why didn’t it work? When we are working with regular objects, we are free to add properties at any time and they stay until you manually remove them. But with primitive wrapper types, properties seem to disappear because the object on which the property was assigned is being destroyed immediately afterward.

And this happens in JavaScript engine:

// what the JavaScript engine does
var name = "Lorem";
vat temp = new String(name);
name.last = "Ipsum";
temp = null;                // temporary object destroyed

var temp = new String(name);
console.log(temp.last);     // undefined
temp = null;

We can see what JavaScript engine has done. Instead of assigning a new property to a string, the code has actually creates a new property on a temporary object that is already destroyed. And when you try to access that property later, a different object is temporarily created and the new property doesn’t exist there. Although reference values are created automatically for primitive values, when instanceof checks for these types of values, the result is false.

var name = "Lorem";
var count = 5;
var found = false;

console.log(name instanceof String);      //false
console.log(name instanceof Number);      //false
console.log(name instanceof Boolean);      //false

The instanceof operator returns false because a temporary object is created only when a value is read. Because instanceof doesn’t actually read anything, no temporary objects are created, and this tells us that values aren’t instances of primitive wrapper types. It has to be noted that we cannot use String, Number and Boolean objects as you would primitive values. Even though the typeof evaluated to true.

-By
Uma Maheswar
Helical IT Solution

Document Fragments

The one of the most underrated feature of JavaScript is DocumentFragment. DocumentFragment is a DOM Node-like parent which has node-like properties/methods and is not a part of the actual DOM tree. It can be used for better performance. A DocumentFragment can be created using document.createDocumentFragment method.

Example Usage

Let us assume that we have to create a long list using ul.

<ul is="list"></ul>

Since DOM mutations are very expensive, we have to minimize the number of mutations possible. So instead of appending the items to ul directly, we will use a DocumentFragment.

var fragment = document.createDocumentFragment();

This DocumentFragment will act as DOM node on which we can attach our elements

for (var i = 0; i < 1000; i++) {
  var li = document.createElement("li");
  li.innerHTML = "Item #" + i;
  fragment.append(li);
}

Now we can append the DocumentFragment to ul.

document.getElementById("list").appendChild(fragment).

Using DocumentFragment is much faster than repeated single DOM node operations.

Arrays in JavaScript

Here is the question.
Suppose you are given two arrays as key, value pairs and asked you to associate them as Object with the same, who would you do that? So, here is the solution for it.

    function associateArrays(keys, values) {
        if(!Array.isArray(keys) || !Array.isArray(values)) {
            throw new TypeError("Expected two Arrays");
        }
        var result = {};
        for(var i = 0; i < keys.length; i++) {
            result(keys[i]) = values[i];
        }
        return result;
    }


    var split = associateArrays(["0", "1", "2"], ["a", "b", "c"]);
    split;
    //Object {0: "a", 1: "b", 2: "c"}



Here is another question.
Suppose say that you are given an array and asked to multiply each item in the array and return the result. SO here is the solution for it.

    function multipleArrayItems(arr) {
        if(!Array.isArray(arr)) {
            throw new TypeError("Expected an array");
        }
        if(arr.length < 2) {
            throw new TypeError("The array should at least have 2 items");
        }
        var product = arr[0];
        for(var i = 0; i < arr.length; i++) {
            product *= arr[i];
        }
        return product;
    }


    var product = multipleArrayItems([2, 2, 4, 4]);
    product; // 64


-By
Uma Maheswar
Helical IT Solution

Why Browser Detection is Bad ?

It is against the spirit of web standards

The whole reason that web standards exist is so that we don’t have to write specific code for specific environments. We should write code that adheres establishment of standards and software in charge of displaying our code should display it as the standards dictate.

It relies on the browser user-agent string,which has a hilariously disastrous history and it is easily spoofable. Also tt can hinder devices

Example:

you detect for the iPhone and serve is special content. Now the iPhone can never see the web page as other browsers see it, despite it being fully capable of doing so.

why we do it?

We do it because different browsers handle things differently and browser detection can get us out of a pinch and get things working how they should.

sometimes the situations leading up to us resorting to browser-detection are rage-inducing. But remember it’s often not the browser that is at fault. Even in the case of IE 6, it was the most standards-compliant and advanced browser of it’s time when it was released. And some of the standards that we have today were not complete at that time.

What should we do instead?
Real-world web design sometimes needs quick fixes, and making damn sure features work as intended. This doesn’t always allow for altruistic choices that leave out some functionality because it is the “right thing to do.”

Ideally
we would do capability testing. That’s the information we really need right? Test if the environment we are in is capable of what we want to do. If it is, do it.

-By
Nitin Uttarwar
Helical It Solution

Inheritance by Borrowing a constructor – JavaScript

Inheritance by borrowing a constructor will allow us to call a function and then pass an object that the function should bind to this value. So, for the sake of inheritance purpose, the child constructor calls the parent’s constructor and then binds the child’s newly-created this object as the parent’s this.

So let’s define parent constructor first:

function Shape(id) {
    this.id = id;
}

Shape.prototype.name = 'Shape';
Shape.prototype.toString = function() {
    return this.name;
}



Now, let us define another function which uses apply() to call the above created function constructor, passing this and any additional arguments.

function Triangle() {
    Shape.apply(this, arguments);
}

Triangle.prototype.name = 'Triangle';



It can be seen that both the constructor functions have added some extra properties to their prototypes. Now, let’s test this by creating a new triangle object:

>var test = new Triangle(101);
>test.name;
"Triangle"



The above triangle object has inherited the id property from the parent but it doesn’t inherit anything that has been added to the parent’s prototype.

>test.id;
101

>test.toString();
"[object Object]"


So, why did the triangle failed to get the Shape function’s prototype properties? It is because, there was never a new Shape() instance created. And hence the prototype was never used. So, how can we achieve this?

function Triangle() {
    Shape.apply(this, arguments);
}

Triangle.prototype = new Shape();
Triangle.prototype.name = 'Triangle';



In the above code, the parent’s own properties are recreated as the child’s own properties. If a child inherits an array or an object, it will be completely a new value (which is not a reference) and modifying this won’t affect the parent.

Everything is well and good till now but we have a drawback here and that is, we are calling the parent’s constructor twice. How? – Once with apply() which is used to inherit own properties and once with new to inherit the prototype. If we look closely, the own properties of the parent are inherited both the times. let’s simplify this:

function Shape(id) {
    this.id = id;
}

function Triangle() {
    Shape.apply(this, arguments);
}

Triangle.prototype =  new Shape(101);



Now, by creating new instance:

>var test = new Triangle(202);
>test.id;
202



Therefore, we have own property id, but there’s also one that comes down the prototype chain, which is ready to shine through:

>test.__proto__.id;
101

>delete test.id;
true

>test.id;
101



So, to mitigate double calling, what we can do is: First, we can call apply() on the parent constructor to get all its own properties and then copy the prototype’s properties using a iteration in the child constructor.

Arrays & Objects (in OOP)

In this post, we first discuss Arrays in a loop and then we move on to Objects in Object Oriented JavaScript Programming.

So, there is an array as:

var input = ["js", "css"];

var config = {
    "build" : ["js", "css", "version"],
    "js" : ["core", "react", "angular"],
    "css" : ["less", "sass"]
};

var tasks = [];

getTasks(input);

function getTasks(input) {
    input.forEach(task => {
        if(config[task]) {
            getTasks(config[task]);
        }
    })
}



At this time, if we call tasks, we get ["core", "react", "angular", "less", "sass"]. If we add "version" to the variable build then the function getTasks doesn’t work and to that, we need an else condition. Hence the function now looks:

function getTasks(input) {
    input.forEach(task => {
        if(config[task]) {
            getTasks(config[task]);
        } else {
            tasks.push(task);
        }
    })
}



Now, if we call tasks, we get ["core", "react", "angular", "less", "sass", "version"].

Everything works till here. Suppose if we want to call build in the variable input, our logic fails because it just results ["js", "css", "version"] rather than ["core", "react", "angular", "less", "sass", "version"]. So, how can we achieve that? Well, one method is to loop once again in forEach method and the code goes like:

function getTasks(input) {
    input.forEach(task => {
        if(config[task]) {
            if(config[task]) {
                getTasks(config[task]);
            } else {
                tasks.push(task);
            }
        } else {
            tasks.push(task);
        }
    })
}



By looking at the code, it can be easily said that there is mess. So how can we resolve this problem with neat and clean code? Well, we have recursion for that. And that can be rewritten as:

function getTasks(input) {
    input.forEach(task => {
        if(config[task]) {
            getTasks(config[task]); //recursive function
        } else {
            tasks.push(task);
        }
    })
}


So, we are calling the same function inside so that it handles the loop without mess and you achieve the same output by calling tasks.

Next, we move on to Objects. So, what we are going to do now is, we are going to write a constructor function that takes some properties and methods. We discuss some of the techniques in the same.

var Person = function(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.getFullName = function() {
        return this.firstName + " " + this.lastName;
    };
    this.greet = function(person) {
        if(person instanceof Person) {
           return "Hello ", person.getFullName();
        } else {
            return "Hello there!!";
        }
    };
};



So to invoke the Person Object we call it as:

var person = new Person("John", "Doe");



Now, if we call person we get the Person object with all its properties.

Suppose say that you want to create the object person without new keyword. How would you do it? If we just write:

var person = Person("John", "Doe");
person.getFullName();



we get an error stating that: Property 'getFullName' of object # is not a function. The error generates because getFullName method is not on the top window. So, how do we achieve that? Here is the simple solution:

if(this === window) {
    return new Person(firstName, lastName);
}


So the total code will be:

var Person = function(firstName, lastName) {
    if(this === window) {
        return new Person(firstName, lastName);
    }
    this.firstName = firstName;
    this.lastName = lastName;
    this.getFullName = function() {
        return this.firstName + " " + this.lastName;
    };
    this.greet = function(person) {
        if(person instanceof Person) {
           return "Hello ", person.getFullName();
        } else {
            return "Hello there!!";
        }
    };
};

var person = Person("John", "Doe");
person.getFullName(); // John Doe


Everything is fine so far but still we can enhance the code because, suppose consider that a created Object doesn’t require all the properties rather it just want few properties and methods. So, instead of calling the required properties and methods, we are attaching every method and properties and this causes overhead. Therefore, we can the above code into pieces using prototype. Foe example:

Person.prototype.getFullName = function() {
    return this.firstName + " "+ this.lastName;
};

Person.prototype.greet= function(person) {
    if(person instanceof Person) {
       return "Hello ", person.getFullName();
    } else {
        return "Hello there!!";
    }
};


Can we once again redefine it? – Yes.. like this:

Object.defineProperties(Person.prototype, {
    fullName : {
        get: function() {
            return this.firstName + " " + this.lastName;
        }
    },
    greet: function(person) {
        if(person instanceof Person) {
           return "Hello ", person.getFullName();
        } else {
            return "Hello there!!";
        }
    }
});



That’s all for this post. In the upcoming posts, we discuss one logic in either JS or jQuery and will continue the second part with OOP in JS.

-By
Uma Maheswar
Helical It Solution

Getters and Setters of JavaScript for a Java Programmer

Getters and Setters of JavaScript for a Java Programmer

In this blog article I will discuss about an important feature of JavaScript – property Getters and Setters. Getters and Setters help you to achieve data encapsulation. The write up is not going to be a comprehensive tutorial but, will provide some insights to understand the world’s most popular programming language properly (from the stand point of a Java Developer – like myself 🙂 ).

Getters and Setters

JavaScript getters and setters work different than Java getter and setters though the purpose is the same – encapsulation. First I will brief about the Java getters and setters and then next I will discuss about JavaScript getters and setters.

A typical Java POJO looks like this.

 

    class Person {
        private String firstName;
        private String lastName;

        Person(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        //The rest of the methods like equals(), toString() and hashCode() may go here.
    }

    

Here getters and setters are typical(mostly generated by using IDEs 🙂 )


        Person person = new Person("John", "Skeet");
        person.getLastName();//Skeet
        person.setLastName("Doe");//Access the method to set the lastName property
    

These methods get and set the member variables firstName and lastName.
The methods g[s]etXXX can be used to have control over the values of firstName and lastName. For more information on this pattern refer to

Why Getters and Setters?

Being a Java developer one may tend to write the same in JavaScript like the following.


        function Person(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;

            //Function expression; all the vars are hoisted, but assignments are not hoisted.
            //Functions are defined as values. If the value of a var is a function then 
            //it is known as a method.

            //And in JS, private methods don't have access to the public 
            //variables(firstName and lastName)
            //Because inner functions don't share the context of the parent scope

            //Here all the vars(whether value or function) are scoped to the function.
            //They are undefined outside.

            var getFirstName = function() {
                return this.firstName;
            }

            var setFirstName = function(firstName) {
                this.firstName = firstName;
            }

            var getLastName = function() {
                return this.lastName;
            }

            var setLastName = function(lastName) {
                this.lastName = lastName;
            }
        }

        var person = new Person("John", "Skeet");

        //The following is a public method that is available to all the live objects and 
        //future objects of type Person. This method is inherited from an object called the
        //prototype of the Person constructor function

        Person.prototype.toString = function() {
            return this.getFirstName() + " " + this.getLastName();
        }

        document.writeln(person);

    

Or like this…


        function Person(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;

            //All these are now privileged methods - as what they call -
            //These methods have access to all the vars(values and functions)
            //that are visible with in the function scope along with the properties
            //assigned to 'this' (values and functions) as they are defined on 'this'.

            this.getFirstName = function() {
                return this.firstName;
            }

            this.setFirstName = function(firstName) {
                this.firstName = firstName;
            }

            this.getLastName = function() {
                return this.lastName;
            }

            this.setLastName = function(lastName) {
                this.lastName = lastName;
            }
        }

        var person = new Person("John", "Skeet");

        Person.prototype.toString = function() {
            return this.getFirstName() + " " + this.getLastName();
        }

        document.writeln(person);
    

But, both these patterns are not the ways to write getters and setters in JavaScript. In fact, the first template will throw error.


    Uncaught TypeError: this.getFirstName is not a function(…)
    

Because getFirstName is a variable inside the Person constructor, which is a function that is not visible outside the scope. Because its scope is function scope.

The second template works fine without any errors and it gives the value ‘John Skeet’. But the methods are normal methods (like any other method) of the person object. And by the way, one can directly access the properties without the need of those methods.


        person.firstName = "Osama";//boom
    

So, the correct way of achieving the encapsulation in JavaScript is by using the Object.defineProperty() method.


        var Person = function() {
            var first_name,
                last_name,
                that;

            that = this; //Parent context for use by inner functions

            //Your private functions and other variables go here

            Object.defineProperty(this, "firstName", {
                get: function() {
                    //Here we are not returning firstName. We are returning first_name
                    return first_name;
                },
                set: function(value) {
                    if (typeof value === 'string' && value.length > 3) {
                        first_name = value;
                    }
                },
                configurable: true,
                enumerable: true
            });

            Object.defineProperty(this, "lastName", {
                get: function() {
                    //Here we are not returning lastName. We are returning last_name
                    return last_name;
                },
                set: function(value) {
                    if (typeof value === 'string' && value.length > 3) {
                        last_name = value;
                    }
                },
                configurable: true,
                enumerable: true
            });
        };

        var person = new Person();
        //See, No arguments. First time if you call person.firstName you get undefined
        person.firstName = "John";
        person.lastName = "Skeet";
        document.write(person.lastName); //Skeet
        document.write(person.firstName); //John
        person.lastName = "Doe"; 
        //Now setter is called, but it has rejected the value as Doe is only three characters
        document.write(person.lastName); //Skeet

    

Using the object literal way…….


        var person = {
            name: 'John Skeet',
            get getName() {
                return this.name;
            },
            set setName(name) {
                if (typeof name !== 'string' || name.length < 3) {
                    throw new Error("Person name can't be empty and 
                          should be more than 3 characters");
                }
                this.name = name;
            }
        }

        document.writeln(person.getName());//Expecting John Skeet?
        //Noo... You will get 
        //Uncaught TypeError: person.getName is not a function(…)
        //Because getName is a property of the object person, which invokes a function

        document.writeln(person.getName);//Expecting John Skeet? You got it. Its not a method
        //Now, don't do this...  person.setName("John Doe");
        //Do this

        person.setName = "John Doe";

        document.writeln(person.getName); //John Doe
    

Another alternative by using Java way of getName and setName is ….


        var Person = function(name) {
            var name,
                isValidName = function(name) {
                    if (typeof name !== 'string' || name.length < 3) {
                        throw new Error("Person name can't be empty 
                              and should be more than 3 characters");
                    }
                    return true;
                };

            if (isValidName(name)) {
                name = name;
            }

            this.getName = function() {
                return name;
            };

            this.setName = function(value) {
                if (isValidName(value)) {
                    name = value;
                }
            };
        };

        var john = new Person("Doe");

        document.writeln(john.getName());//Doe

        john.setName("");
        //Uncaught Error: Person name can't be empty and should be more than 3 characters(…)
    

Hope you have enjoyed learning the worlds’s most misunderstood but highly expressive language – JavaScript.
Wish you happy functional programming…

–Rajasekhar
Developer,
Helical IT Solutions.