Arrow function (Lambda expression) in Brief

What is Arrow function?

Arrow function expression defines the succinct syntax for writing the function expressions in JavaScript, which has been introduced in the ES6. It will not bind its own this, while using it within the functions and it has in-built return type attribute.

Syntax:

(parameters) => {stuffs}

Example:

Following is the simple demonstration about the usage of Arrow functions to make the code more compact.

var marks = [68, 83, 72, 56, 88];
var sum1 = marks.reduce(function (total, mark){
    return total + mark;
});
console.log(sum1);// Output: 367

var sum2 = marks.reduce((total, mark) => {
    return total + mark;
});
console.log(sum2);// Output: 367

var sum3 = marks.reduce((total, mark) => total + mark);
console.log(sum3);// Output: 367

Fiddle Demo

Advantage of Arrow function:

Example with JavaScript object constructor

In the following example the student () constructor has setTimeout () method for updating the “totalMark” attribute of “student ()”. Here the “this” defined by setTimeout () method is refers to the Window object. Hence it will not match with the “this” defined by the student () constructor. So the “totalMark” attribute of student () constructor cannot be changed in setTimeout () method as expected and it results in TypeError.

var s = new student();
function student() {
    this.student1 = { "name": "Smith", "totalMark": 375 };
    //To change the "Total Mark"
    setTimeout(function () {
        var newTotal = 395;
        if (this.student1.name == "Smith")//Uncaught TypeError: Cannot read property 'name' of undefined
            this.student1.totalMark = newTotal;
    }, 500);
}

To overcome this issue in ES6, Arrow function expression can be used with that setTimeout () method as stated in the following code snippets.

var s = new student();
function student() {
    this.student1 = {"name":"Smith", "totalMark":375};
    //To change the "Total Mark"
    setTimeout(() => {
        var newTotal = 395;
        if (this.student1.name == "Smith")
            this.student1.totalMark = newTotal;
        console.log(this.student1);//{name:"Smith",totalMark:395}
    }, 500);
}

 

Disadvantage of Arrow function:

In the following example, while using the Arrow function inside the marks () function prototype for total () method, it will change the context of “this” to Window object. Hence it leads to unexpected output or error.

var marks = function() {
    this.mark1 = 80;
    this.mark2 = 60;
};

marks.prototype = {
    total: () => this.mark1 + this.mark2 //Here "this" refers to Window object. It does not represents the "this" of marks()
}
var m = new marks();
console.log(m.total()); //NaN

So in this case, writing the function expression in normal way is preferable as like as following code snippets. Here in total () method, “this” will be referred to marks () object constructor and it works as usual without exception.

var marks = function () {
    this.mark1 = 80;
    this.mark2 = 60;
};

marks.prototype = {
    total: function () {
        return this.mark1 + this.mark2;
    }
}
var m = new marks();
console.log(m.total()); // 140;

 

Note:

For Arrow function line break is not acceptable as shown below. It will throw Syntax error.

var sum = ()
=> {return true}; //As arrow symbol at starting position

 

Angular 2 @NgModule.scheme, what does it actually do?

When working with Angular 2 components, sometimes I came up with below error.

1

And googling tells me to set @NgModule.scheme as to CUSTOM_ELEMENTS_SCHEMA which resolve this issue.

So, for what purpose this scheme option is and what does it actually tells the Angular?

The NgModule’s scheme property tells the Angular compiler the type of component it wants to expect from the template. The available schema options are,

  1. CUSTOM_ELEMENTS_SCHEME.
  2. NO_ERRORS_SCHEME.

Default

By default, the compiler will check for Angular components in its template. When the selector is not matched with any of its declarations then it will check for the value of schema property.

If the selector, you used, is an Angular component and still you are getting this issue then you should double check whether you have properly imported the directive/component in the declarations of NgModule as follows.

@Component({
    selector: 'app-test',
    template: `Hello World`
})
export class TestComponent {
    constructor(){}
}

import { AppComponent, TestComponent }
from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

CUSTOM_ELEMENTS_SCHEME

This tells the compiler to allow any type of custom element in its template. The custom element should have hypen(-) so it’s attributes.

This helps to incorporate Web components other than Angular component in the application.

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  . . . .
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }

NO_ERRORS_SCHEME
Its simple as the name implies it will not show error when there is an unknown selector in the template.

import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';

@NgModule({
  . . . .
  bootstrap: [AppComponent],
  schemas: [NO_ERRORS_SCHEMA]
})
export class AppModule { }

.

Happy debugging.. 🙂

Angular 2 – How to get template reference variable or directive instance inside component

In this post let us see how to get Angular 2 directive/child component instance inside the parent component class.

ViewChild in action
The ViewChild decorator can be used to achieve this requirement.
The ViewChild accepts either the directive type or the template reference variable as argument and set the directive instance to the target property after the view get initiated.

@Component({
  selector: 'child-cmp',
  template: '

child

'
})
class ChildCmp {
  doSomething() {}
}
@Component({
  selector: 'some-cmp',
  template: '<child-cmp></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {
  @ViewChild(ChildCmp) child:ChildCmp;
  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

The ViewChild will set the target property once the component view get rendered hence accessing the property before the view get initiated will return inappropriate result.

You can use the ngViewAfterInit lifecycle hook to identify the view initialization.

Argument as Directive type vs template variable
Using argument as template variable ViewChild is best from my point of view as it will provide access to specific directive instance when having more than one directive in the template.

@Component({
  selector: 'some-cmp',
  template: '<child-cmp #child></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {
  @ViewChild('child') child:ChildCmp;
  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

Happy Scripting.. 🙂

DOM creation and manipulation tips and tricks

In this post, I would like to share a simple DOM creation and manipulation technique which will provide some performance boost.

The goal of this post is to improve browser DOM manipulation performance by reducing unwanted reflow and repaint process. If you are unaware of them you should go through the below topic before getting started with this post.

Reflow and repaint

Use Document fragment
This is an already known technique. Using document fragment allow the separation of DOM creation from live document so that it will avoid unnecessary browser reflow and repaint.

var fragment= document.createDocumentFragment();
fragment.appendChild(document.createElement("div"));

Clone nodes
Cloning already created element using cloneNode. This will be helpful when creating large number of same element. Mostly likely it can be used while creating table tr elements from JSON.

var fragment= document.createDocumentFragment();
var div = document.createElement("div");
fragment.appendChild(div.cloneNode(false));

Batch DOM update
Always batch the DOM update. Batch the DOM changes will reduce browser reflow and repaint.

Using requestAnimationFrame for DOM changes
This technique will provide a considerable performance when changing the live document. requestAnimationFrame will be used to update the DOM changes when the next reflow/repaint happens.
Normally it is introduced to do smooth animation experience in browser but here we can use this to do a single DOM update.

requestAnimationFrame(function(){
  document.body.appendChild( document.createElement("div") );
});

Use insertAdjacentHTML instead of innerHTML
This will be used when we need to append dynamic content to the same element.
We can use the innerHTML as follows.

var div = document.createElement("div");
div.innerHTML ="Hi" //<div>Hi</div>

div.innerHTML += " Dude"; //<div>Hi Dude</div>

But the above one have significant performance impact as it needs to re-parse all the child element already present.
To overcome this we can use insertAdjacentHTML which will append the inner HTML without touching the other elements. It only parses the new HTML need to be appended.

var div = document.createElement(&quot;div&quot;);
div.innerHTML = "Hi";  //<div>Hi</div>

div.insertAdjacentHTML("afterend", " Dude"); //<div>Hi Dude</div>

Following the above methods will provide a better performance in most of the modern browsers.

Happy scripting….

Replace () as call back function

We know that the replace() method will return a new string based on the pattern and its corresponding replacement argument.

Here the pattern can be either general string or regular expression that we normally use. And for replacement argument in most cases we use string as replacement. But there is an extensible facility to use this replacement as call back function.

Here we go with a small example code snippets.

Code Snippets:


var numbers = '34 55 27 45 72',
type1 = numbers.replace(/\d+/g, '*'),
type2 = numbers.replace(/\d+/g, function (item) {
return +item < 50 ? '*' : item;
});
console.log("simple replace() : ", type1);
console.log("replace() with call back function : ", type2);

Fiddle Demo

Note:

The call back function will be invoked for the each matched set of an item, when the first parameter regular expression is declared as global.

Why new keyword should be used while instantiating JavaScript class

The new keyword is used to instantiate prototypical class or other objects. But why we need new keyword to initialize it, when you to try to initialize it without new will not throw any error at all then why should I use new before my class to instantiate it.

The answer is simple new keyword will set the ‘this’ to the new object created using function instead of global scope”.

If you didn’t provided new keyword then the context will be set to window(global scope).

You can see the difference in the below code example.

var fn = function (){
       this.a = 2;
       return this;
}

Instantiating fn without new keyword.

 var f = fn();  //`this` refers window here.

Instantiating fn with new keyword.

 var f = new fn();  //`this` refer object created by `fn` here.

Even though using new keyword is the best practice to instantiate class, most of the time, the users will skip them as it doesn’t provide any error at all.

We can use the below simple workaround to enforce the instantiating process using new keyword. Then the above fn will become as below.

 var fn = function (){
       if(!(this instanceof fn)) //workaround to resolve this problem.
          return new fn();
       this.a = 2;
       return this;
}

Now instantiating without new will also set this to the current object.

 var f = fn();  //this refer to fn here.

Instantiating class/function without new keyword in ES6 will throw TypeError.

Happy Scripting… 🙂

Some alternative use of bit wise operators

In this blog, I am just going to share some of the alternative use of the bitwise operators.

1. Replace Math.floor with double ~~.
Even though JavaScript Math library is well optimized, we can use the bitwise operators to reduce some keystrokes.

~~3.4 //result : 3

2. Convert to Boolean using !!
Double NOT operator is used to convert any type into Boolean.

var d = &amp;quot;Hi&amp;quot;;
!!d //result : true
var f = null;
!!f //result : false

3. Swap values without temp variable using XOR.
It is the one of the common method used to swap two variables without using temp variable.

var a = 5, b= 6;
a ^= b; b ^= a; a ^= b; //result a = 6, b = 5;

4. Using left and right shift with 1 bit to perform multiply and division.
Left shifting a number 1 bit is equivalent to the result obtained by multiplying it by 2 and right shifting 1 bit is equivalent to dividing it by 2.

var d = 4, f = 6;
d >> 1 //result : 4 * 2 = 8
f << 1 //result : 6 / 2 = 3

5. Checking odd/even using AND with 1
Performing AND operation with 1 will return value greater than 0 if its odd. We can use it simply to find whether a number is odd or even.

var a = 5, b= 6;
a & 1//result 1 - odd
b & 1//result 0 - even

Happy Scripting…

Using Jquery Deferred

I am going to give a simple example which would explains the usage of Jquery deferred concept. The Jquery deferred plays a vital role in handling asynchronous actions. The $.Deferred is used internally by many Jquery API such as ajax and animations.

The $.Deferred usage flow will be as follows.

  1. Instantiate deferred object using $.Deferrred() when some action starts.
  2. When the action completed, resolve the deferred object using resolveWith/rejectWith and your parameter.
  3. Return the promise object from the function for chaining ability

Now I am going to explain using $.Deferred object with the simple animation operation.

For that we have a HTML element as follows.

 
<input type="button" value="Animate" />
<div id="target" style="border: solid 1px black; width: 500px; height: 70px;"></div>

And the function which will perform the animation is as follows. The below function will animate the width of the div element from 500px to 10px. I had not written the animate function in a generic way as I am going to concentrate on using deferred promise.

 
    function animate() {

            //Initialize Deferred object.
            var deffered = $.Deferred();   Step 1

            width = +$("#target").outerWidth();

            var inter = setInterval(function () {
                
                $("#target").width(width-- + "px");

                //Stops animation when width reaches 10.
                if (width == 10) {

                    clearInterval(inter);

                    //RESOLVE THE DEFERRED WITH arguments.
          Step 2 deffered.resolveWith($("#Grid"), [{ width: width }]);
                }

            }, 10);
            
            //Returns promise object to chain operation.
         Step 3   return deffered.promise();
        }

Now the animation function can be invoked as follows. And when the animation completed, the promise object will get resolved and call the corresponding callback registered using done. If fails, the callback registered with fail will be invoked.

 
       //Input element click handler.
        function change() {            

            animate().done(function (e) {
                console.log(e.width); //Returns 10
            });

        }

And I said in the Step 3 to return the promise object. But we should be careful in using this since it sometimes led to anti-pattern.

Monkey patching

Monkey patching is a technique that uses the flexibility of the JavaScript to modify any function/method behavior.

Performing monkey patching is simple and it can be done by the following steps.

  1. Store the original function in a variable
  2. Now modify the function behavior
  3. Call the original function using apply.

This can be useful when you want to change the argument values of the function. For example, consider we have the following class.

 


        var math = function () {
            this.a = 1;
            this.b = 2;
        };

        math.prototype = {
            sum: function (a, b) {
                return a + b;
            }
        }

Now we can modify the method sum using the monkey patching technique as follows.


        var original = math.prototype.sum;   Step 1

        math.prototype.sum = function (a, b) {
            a = a * 2, b = b * 2;    Step 2

            return original.apply(this, [a, b]);    Step 3
        }

On executing the above method, the result will as follows.


       var obj = new math();

        obj.sum(1, 2); //return 6;
        //Expected: 3, Actual : 6 due to monkey patch

Happy Scripting… 🙂

Using JSON parse and stringify methods

JSON plays vital role in JavaScript when comes with server interaction. But i noticed when people spoke about JSON they represent it as JSON object in Javascript which is incorrect. JSON is not a object it is just a string format which can be converted to object/array based on its language(Javascript, C#, C++ etc.)

JSON can be converted to JavaScript object using JSON.parse and JSON.stringify vice verse.

JSON.stringify

It is similar to the serialization of the object. The signature of the stringify method is as follows.

JSON.stringify(value[, replacer[, space]])

In the above the first argument is the object/array to be converted to JSON formatted string.

Controlling the stringify operation

Using replacer

The second argument of the stringify method is the replacer which can be an array or function and the value returned from the replacer will be stringify.

Example 1: using array

JSON.stringify({ a:1, b:2, c:null }, ["a","c"]);
//Output: "{"a":1,"c":null}"

Example 2: using function

JSON.stringify({a:1,b:2,c:null}, function(key, value) { return value != null ? value: undefined });
//Output: "{"a":1,"b":2}"
Using toJSON property

It is an another way of customizing the stringify operation. If an object contains a property named toJSON then the value returned from this function will be stringified instead of whole object.


var exFn = function() {
                      this.a=1;
                      this.b=2,
                      this._sum= function() { return this.a + this.b };
                      this.toJSON = function() {
                                             return {
                                                      a:this.a,
                                                      b: this.b,
                                                      sum: this._sum()
                                                     }
                                                }
                    }
//Output: JSON.stringify(new exFn())
"{"a":1,"b":2,"sum":3}"

JSON.parse

It is similar to the de-serialization of the object. The signature of the parse method is as follows.

JSON.parse(text[, reviver])

In the above the first argument is the JSON text input which has to be parsed to JavaScript object/array. For that the JSON string must abide the standards provided by the ECMA-404 The JSON Data Interchange Standard.

Controlling the parse operation

The parse operation can be controlled using the second argument of the parse method. It can be of type function. If the reviver is used then the parse will be done only based on the value returned by the reviver if reviver return undefined then that key will be excluded. The below will exclude the key with null values

var d = "{\"a\":1,\"b\":1,\"c\":null}"
JSON.parse(d, function(key, value){ if(value) return value; });
//Output: Object { a=1,  b=1}