Thursday, May 19, 2016

Spread operator or Rest parameter or Ellipsis in JavaScript (ES6)

Spread/Rest/Ellipsis operator in JavaScript is very useful in many context. First important use of this operator is to pass indefinite number of argument in function

Operator syntax: ...name

Three dot and then a variable name

 function sum(a,b,...n){
  return a+b+n[0]+n[1];
 }
 sum(1,2,3,4); // output: 10 

This is also called rest parameter. inside function it can be used directly as array.

As we already know that arguments is already available in function to get many parameters as shown below: but actually that is not array

function fun(){
 return arguments[0] + arguments[1];
}

fun(1,2); // 3


function fun2(...n){
 console.log(arguments);
 console.log(n);
}

fun2(1,2,3); // it will print arguments object and array n.

There are other advantages of spread operator. Suppose we have 2 arrays and need to merge both

var a = [1,2,3], b = [4,5,6];
a.push(...b);
console.log(a); // [1,2,3,4,5,6]

Sunday, April 24, 2016

AngularJS advanced trick and techniques

These days AngularJS is highly recommended framework for front-end developer. Angular is really awesome framework to work with. Below are few techniques those I feel really cool features and may be these are simple and easy for you but as a fresher in angular I think these features are really good.

1. How to add multiple classes in ng-class?

Everyone knows how to add class using ng-class, its very easy. We can use ng-class to have more than one class as well

 
// single class
// multiple class
some content

Similarly we can add many classes separated by comma (,)

2. Can we have multiple conditions in ng-hide and ng-show?

Yes, we can have multiple conditions in ng-hide and ng-show.

// ng-show with multiple conditions
Some content

3. How to share methods or data between controllers?

Yes we can share data and methods between controllers using Factory or Service. Angular has service as constructor method which instantiate once on startup and we can use this service/factory in any controller within the module by injecting on controller method.

Restrict input to allow only required value (jQuery plugin for input type validation)

HTML5 provides many validation on input, but still few we need to implement by our self. For example, if we need one input for price then we should allow users to enter only float values. I created one small plugin using jQuery, it is very easy to use.

To create one input with only price value then just include attribute "only-price"


To create one input with only number (contact) value then just include attribute "only-number"


Here is the codepen: http://codepen.io/JitendraPal/pen/JXBqXj