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

 

Advertisements

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.. 🙂

Height responsiveness using calc() CSS

I like to share a small use case of calc() CSS which helped me to achieve height responsiveness.

My use case is as follows

  1. A parent element with some static height.
  2. Three child elements (for reference let’s name them as c1, c2 and c3)which should fill the parent.
  3. Out of the three child elements, two of them(c1 & c3) will have static height and the c2 has to occupy the remaining space.
  4. And the c2 has to adjust its height on window resize without disturbing it’s siblings.

To achieve this, I need to calculate the height required by the c2, initially I tried the below solution to find the height.

  1. Calculate the sum of height of two child elements(c1 & c3).
  2. Calculate the height of parent element.
  3. Now height of the last child element calculated from the equation – height of parent – sum of height of c1 & c3 elements.
  4. Set the resultant height to the c2 child element.
  5. To auto adjust the height on window resize, register a resize callback and repeat the step 1 to 4.

Well, this method will work well but it could be done better.

How can it be done better?

Here comes the calc CSS. There are many usages available for calc CSS one of the them is unit mixing which is going to help me with this.

So my requirement will be achieved with the following steps.

  1. Calculate the sum of height of two child elements(c1 & c3).
  2. Now set the height to the c2 child element as height: calc(100% - height from step1).

That’s it. Now all the child elements will fit within its container whereas the c2 child will use the remaining space leave by c1 and c3.

Also it’s worth to note that this will allow the c2 element to adjust its height on window resize without using a resize event handler.

References

  1. MDN: calc CSS
  2. CSS Tricks: A couple of use cases for calc

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.

Deleter – Node based directory removing tool

My first node package deleter, has been released. Its a CLI, which is used to remove directories. I come up with idea to create this when i faced difficulties in deleting node_modules from my node based applications.

Installation

npm install deleter -g

Since it is a CLI, global installation is preferred.

Usage

deleter <directory-name>

Example


deleter node_modules

Limitations

For now, its target for windows operating system and other OS will be considered in upcoming updates.

 

 

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… 🙂