Thursday, October 29, 2015

JavaScript Promises

In today's blog post we will discuss what promises are in JavaScript and how they are useful. In my last week's blog post here, I discussed about callback functions and the callback hell problem. Today, we will see how promises can help us tackle the callback hell problem.

Promise

Promise represents the eventual result of an asynchronous operation. Promise is an object which represents a handle that listens to the results of an async operation. In other words, Promise promises to alert you when async operation is done and return the results.



Promises in JavaScript


As we know, in the nested callbacks, it's really difficult to manage and debug the code and it gets worse with more nesting. For example, if you have something like this:

function load(){
  var connection = new connection();
  connection.loadBook(function(err, connection){
      connection.loadChapter(function(err, connection){
          connection.loadPages(err, function(err, collection){
          });
      });
  }); 
}

You can see this is getting ugly and will be difficult to manage. Now, on top of it, if you add error handling to each and every call, the function may look something like this:

function load(){
   var connection = new connection();
   try
   {
       connection.loadBook(function(err, connection) 
       {
           try
           {
               connection.loadChapter(function
                    (err, connection) 
               {
                   try
                   {
                     connection.loadPages(err, 
                 function(err, collection) 
                       {
                       });
                   }
                   catch(ex)
                   {
                       //handle exception for load chapter
                   }
               });
           }
           catch(ex)
           {
               //handle exception for load chapter
           }
       });
   } 
   catch(ex)
   {
       //handle exception for load book
   } 
}


You can see the point, it's even more ugly and difficult to manage. This is called callback hell problem.

Promises

Promises are used to solve the callback hell problem. Promises are part of libraries like jquery, Q, RSVP and are also part of ES6. Let's understand the basics first.

A promise has 3 different states:
i)   PENDING       - not done yet
ii)  FULFILLED   - done
iii) REJECTED     - error
There is also a 4th stage i.e. SETTLED which means that promise is either Fulfilled or Rejected. 

When we create a promise, we need to pass in 2 different methods:
i)  resolve - method that's called on successful completion of promise
ii) reject   -  method that's called on error


var promise = new Promise(function(resolve, reject) {
  if (1==1) {   //we can decide any condition here
    resolve("Promise worked!");
  }
  else {
    reject(Error("Promise failed"));
  }
});
promise.then(function(result) {
  console.log(result); 
}, function(err) {
  console.log(err); 
});

When we invoke the promise using "then", we pass in the functions that need to be used for resolve and reject.

So the example code we saw with callback hell problem above, might look something like this with promises:

function load()
{
    var connection = new connection();
    connection.getbook().then(function(book){
       return getChapter(book.id);
    }).then(function(chapter){
       return getPages(chapter.id); 
    }).then(undefined, function(error){
       //handle error
    })
}

As you can see the code looks so much better with promises. The error handling has been simplified too. The last "then" in the code above uses only reject function, so we passed undefined for resolve function there and only reject function has the value.

Conclusion

Promises help us write asynchronous code in a much cleaner and efficient way. As asynchronous code is becoming more and more prevalent, promises are being used more often.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, October 22, 2015

Callbacks in Javascript

In today's blog post, I will be talking about what callback functions are and their advantages and disadvantages in JavaScript. Callback is a functional programming technique which allows the use of functions as arguments.

Callback Functions

Simply stated, a callback is a function that is passed as an argument to another function. For example,

setTimeout(function() {
    console.log('abhi');
}, 2000);                     //prints 'abhi' after 2 seconds

In the above example, we used a function which just logs one word to the console. The function passed to setTimeout function is the callback function. setTimeout is an inbuilt function in JavaScript which executes the argument function after specified number of milliseconds.
We can pass callbacks either anonymously (as above example) or as a named function (as shown below).




setTimeout(logger, 2000);
var logger = function() {
    console.log('abhi');  //prints 'abhi' after 2 seconds
} 

This code sample does the same thing as one above, except this time named function is used.

Writing own callbacks

We can easily write our own callbacks. Here, we created a simple objLogger function which prints all the object's own properties and their corresponding values. This objLogger function is then used as a callback. The changeName function simply executes the callback function and passes the object to it. The objLogger function prints the property name and it's value.  

var objLogger = function(obj){
  for (var item in obj){
  if(obj.hasOwnProperty(item)){
     console.log(item + ': ' + obj[item]);
    }
  }
}

var changeName = function(obj, callback){
  obj.name = 'abhi2';
  callback(obj);           //callback function execution
}

var obj1 = {name: 'abhi'};
changeName(obj1, objLogger);       //name: abhi2

Another good practice when using callbacks is to check their type before executing them.

if( typeof callback === 'function'){
    callback(obj); 
}


Synchronous & Asynchronous Callbacks

The setTimeout examples that we saw earlier were callbacks which are executed asynchronously. The logger function that we just saw was executed synchronously. So we can use them in both ways in similar way.
The callbacks are used more often in the asynchronous context (for example, Node.js). However, please note, just by using callbacks our code doesn't automatically become asynchronous. If we are writing our own callbacks, we can use them either synchronously or asynchronously.

Callback Hell Problem

When we write a lot of nested callbacks the code looks unwieldy and difficult to understand. This problem of nested callbacks is known as callback hell problem.

Suppose, we have an example where we load a book first, then we load it's chapters and then we load pages and so on... We want to do that asynchronously and on success of previous one, the next call goes out. The code may look something like this:

var connection = new connection();
connection.loadBook(function(err, connection) {
    connection.loadChapter(function(err, connection) {
        connection.loadPages(err, function(err, collection) {
        });
    });
}); 

As you can see the code has started looking bad with multiple nested callbacks. In case of complex code, this might go several layers. Such a code is not only difficult to read but also to debug.
One way to combat this is to always use named functions instead of anonymous functions. That will make it somewhat easier to read. I will be discussing more on how to combat this callback hell problem in my next week's blog post.

Conclusion

Callbacks are used very commonly in JavaScript code. A proper understanding of these helps us write better code and understand the pre-written code better. These are used extensively in various JavaScript libraries and frameworks.



Thursday, October 15, 2015

Function Invocation Patterns in Javascript

In today's blog post, I will be discussing the four different ways in which functions can be invoked in JavaScript.
Other than the declared parameters, every function receives two additional parameters: "this" and "arguments". In object oriented programming, the "this" parameter is very important and we will see how "this" is set in each pattern in this post.


Function Invocation Patterns in JavaScript



Method Invocation

When a function is a property of an object, it is called a "method".  This is the pattern of invoking a function that is part of an object.

var obj = {
    value: 0,
    increment: function(){
            this.value++; 
     }
} 
obj.increment();
console.log(obj.value); 

increment function is part of object obj. The object that is used to invoke the function constitutes "this" in case of method invocation pattern. JavaScript binds "this" at execution time a.k.a. late binding.

Function Invocation

When a function is not a property of an object and is simply invoked using (), that's function invocation pattern.

var sum = add(2,7);

When a function is invoked using this pattern, "this" is associated to the global object. This behavior can lead to confusing errors. Let's take a look at an example:

var name = 'abhi';
var person = {
    name: 'jain',
    printName: function(){
        var helper = function(){
             console.log(this.name)
        }
        helper();   //function invocation pattern           
    }
}

person.printName();         //abhi


Since printName function was defined inside person object, I was expecting the printName function to use the name property from person object. But since printName uses a helper function and the helper function is invoked using function invocation pattern, it associates "this" to global object. As a result, global variable's value is printed.

An object's method cannot use an inner function to help do it's work because the inner function does not have access to the object. The "this" for the inner function is bound to wrong value.
In order to allow inner function to access the object, we can assign the value of "this" to another variable and use that variable in the inner function. Conventionally, that variable is called "that". 

var name = 'abhi';
var person = {
    name: 'jain',
    printName: function(){
        var that = this;
        var helper = function(){
             console.log(that.name)
        }
        helper();   //function invocation pattern          
    }
}
person.printName();    //jain



Constructor Invocation

When we invoke a function using new keyword, it's called constructor invocation pattern.
In this case, a new object is created with a hidden link to the value of the function's prototype member and "this" will be bound to that new object.
JavaScript's prototypal inheritance nature is explained here. JavaScript offers object making syntax similar to classical languages like Java, C# etc with new keyword. This obscures the language's true prototypal nature. 

function Person(type){
  this.type = type;
}
var employee = new Person('employee');

console.log(employee.type);         //employee

Conventionally, the functions to be used with this pattern are kept in variables with capitalized name. 
In this example, the function Person when called with new keyword, returns an object with one property called type. The value of type property is set to the argument passed. 

If a function is intended to be used with this pattern, and somewhere in the code, new keyword is missing, it can lead to difficult to find errors. So we should be careful of the naming convention as that is the only savior.

Apply Invocation

The apply method is defined on every function. We can call the function using this apply method. By using the apply method, we can pass the arguments as array and explicitly choose the value of "this".

var add = function(num1, num2) {
        return num1+num2;
}

array = [5,4];

add.apply(null,array);    //9

So here we passed the arguments as array. 
In the next sample, let's see how to set the "this" object for the function:

var showName = function(){
    console.log(this.name);
}

var obj = {
  name: "Abhi"
}

showName(obj);       //abhi 

If we look inside the add method, we can see the apply and call method:

Call and Apply in function
Similarly, we can use add function using call method as well. Call method is similar to apply method except instead of having arguments as array, we provide list of arguments as seen in the example below:

var add = function(num1, num2) {
        return num1+num2;
}

add.call(null,5,4);      //9

Conclusion

It is important to understand these different patterns because it's very confusing and can lead to hard to find bugs in our JavaScript code. JavaScript has it's own peculiarities and better understanding of these can help us write better code and avoid the bad parts of the language.

Ref: Javascript: The good parts by Douglas Crockford

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, October 8, 2015

Prototypal Inheritance in Javascript

In today's blog post I will be discussing the prototypal inheritance in JavaScript.

Prototypal Inheritance in JavaScript

In most languages (like Java, C#, etc) inheritance is class based. We derive one class from another to reuse the pre-written code and establish hierarchy of different types so we can use them easily throughout our application.


Prototypal Inheritance in Javascript

JavaScript does not have concept of classes. The object themselves carry their data and capabilities. The lineage of the object doesn't matter, only what they can do. JavaScript is a prototypal language i.e. objects inherit from one another.

Let's understand this one by one with examples. The first thing that we need to understand is that functions in JavaScript are objects. So if we have a function named person, we can add any property to it, e.g. type.
 
function person(){}
person.type = 'employee';
console.log(person.type);    //employee

Next, I want the person to be of different types. So I add a type property and return that object.

function Person(type){
  this.type = type;
}

var employee = new Person('employee');
var manager = new Person('manager');

console.log(employee.type);      //employee
console.log(manager.type);        //manager

Please note that this time the function name is capitalized. It's just a convention followed by JavaScript developers that this function needs to be used with new keyword to create instance of Person (I will be writing blog post on constructor invocation next week). So I added this property called type which we pass when we create the object. So we passed 'employee' and 'manager' as the type in the constructor. Invoking new Person('employee') returns the "this" object with type property set to the parameter value.


Next, I want to add smile method to the Person. So you might think by adding it to Person should suffice like this:

function Person(type){
    this.type = type;
}

Person.smile = function(){
    console.log("Smile");
}

var employee = new Person('employee');

console.log(employee.smile());       //employee.smile is not a function
console.log(employee.__proto__);  //contains no smile method   
console.log(Person.smile());           //Smile


As you can see by adding it to Person object, we don't automatically add it to the instances of the Person object. The smile method is available on Person but not on employee. The reason being when we call new Person('employee'), we return the "this" object which has only one property called type defined. Since Person.prototype does not have smile method and employee.__proto__ is created from Person.prototype we will find that there is no smile method in employee.__proto__ as well.

The way Javascript works is, when we look for a property or a method on an object, it's looked up in the following order:

1. employee object has smile method()
2. Employee.prototype has smile method() defined explicitly
3. Person prototype has smile method. Since employee prototype is created using Person prototype object (inheritance).


So, one simple way of adding the smile method to returned objects can be this:

function Person(type){
   this.type = type;
   this.smile = function(){
    console.log("Smile");
    }
}

var employee = new Person('employee');
var manager = new Person('manager');

console.log(employee.smile());          //Smile
console.log(manager.smile());            //Smile


Another way of accomplishing the same thing (which we are more interested in) can be by adding it to the Person's prototype like this:

function Person(type){
   this.type = type;
}

var employee = new Person('employee');
var manager = new Person('manager');

Person.prototype.smile = function(){
    console.log("Smile");
}


console.log(employee.smile());      //Smile
console.log(employee.__proto__); //contains smile method
console.log(manager.smile());        //Smile

Now employee and manager have smile method. This time, the smile method was defined in Person prototype which sets the employee and manager's prototype. Voila, this way we were able to inherit using prototype. 

Now, let's just use the type property inside the smile method to show which type of employee is calling the smile method:

function Person(type){
  this.type = type;
}

var employee = new Person('employee');
var manager = new Person('manager');

Person.prototype.smile = function(){
    console.log("This is "+ this.type +  " smile");
}

console.log(employee.smile());   //This is employee smile
console.log(manager.smile());     //This is manager smile

Next, to further improve, if we want to have separate function for Employee, we can do like this:

function Person(type){
  this.type = type;
}

Person.prototype.smile = function(){
    console.log("This is "+ this.type +  " smile");
}

function Employee(){
    //calling constructor and passing "employee" as type
    Person.call(this, 'employee');
}

Employee.prototype = Object.create(Person.prototype);

var employee = new Employee();

console.log(employee.smile());     //Smile

Here, we created Employee function which returns a Person object and passes "employee" as type. Here, we set the Employee prototype explicitly to create an object using Person prototype. As a result, we inherit everything from Person's prototype. This is what happened internally in the previous examples we saw where smile() was inherited from Person's prototype.

Conclusion

The prototypal inheritance is a powerful concept and it's very different from other common languages like C# and Java. That is why its very important to understand this properly.
So in this article we saw how to implement inheritance in JavaScript and understood the underlying concept.

Image Ref: here

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, October 1, 2015

Augmenting Types in Javascript

In today's post, I will be discussing the advantages of augmenting types and how to accomplish that in Javascript.

Augmenting Object

Augmenting is the mechanism of extending characteristics of a thing by adding new things. That characteristic is then available to all the instances of that thing.
So in case of an object, by adding a method or property to Object's prototype, we make it available to all objects.

For example,

var person = {

   "FirstName" : "Abhi",

   "LastName": "Jain"

}

console.log(person.FirstName);

console.log(person.email);            //undefined

As you can see in the example, the email property was not available for the person object. By adding email to Object's prototype, we make it available to all objects. This is called augmenting the Object.prototype.

Object.prototype.email= "xyz";

console.log(person.email);           //xyz 

Similarly, we can augment Object.prototype to add new methods which will become available to all the objects. 

Augmenting Types

In the same way, we can augment functions, booleans, arrays, strings, numbers and regular expressions. This can come in handy, when we need to implement some functionality to be used across the board. For example, we can add integer function to Number to return the integer part of the number. We can do it like this:

Number.prototype.integer = function(){

      return Math[this < 0 ? 'ceil' : 'floor'](this);

}

console.log((-11 / 3).integer());

Similarly, we can add trim method to String which will simply remove the extra spaces.

String.prototype.trim = function(){

     return this.replace(/^\s+|\s+$/g, '');

}

console.log("  Abhi  ".trim());       //"Abhi"

Now the trim method will be available for all strings.

Caveat

Modifying Object.prototype (and others like Number.prototype, etc) is usually considered evil and frowned upon. The reason being namespace collision. Suppose, one library adds Map method to Object with some implementation and another library also adds Map method with another implementation, so the latter one overrides the former one. This might lead to broken functionality and hard to maintain code.

Another problem is that for-in statement interacts badly with prototypes. When we do a for in loop like this: 

for (var key in person)

{

     console.log(key);   

}

we get FirstName, LastName and Email. Although Email is not person object's own property, it still pops up in the loop. One way to mitigate this is to use hasOwnProperty like this:

for (var key in person)
{

    if(person.hasOwnProperty(key))

    {

        console.log(key);

    }

} 

This will show only FirstName and LastName.

Conclusion

In this post, we saw one of the powerful features of Javascript on how to augment types and how it can be useful to us. We can use this feature to help us add generic functionality which might be needed at multiple places. Some of these things are not that relevant anymore as there are lots of Javascript libraries which give us most of the functionalities we need. However, if we need something custom for ourselves these can come in handy.
Also, such native augmentation should be used when you know that you are working in a controlled environment.

Ref: Javascript - The Good Parts by Douglas Crockford

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)