Arrow functions in Javascript

Standard

Let’s meet our buddy called arrow function. What are they?

Arrow functions are short hands for writing a function which doesn’t need a name and works in lexical scopes.

As per mozilla:

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.

#Let’s see how they look.

Arrow Function
(param1, param2) => {statement}
(param1, param2) => expression
//OR/
(param1, param2) => {return expression;}
(param1) => expression
param1 => expression
//parenthesis are not required in
//case of single parameter.

Equivalent normal definitions are as follow in same order.

Normal Function
function (param1, param2) {
  statement;
}
function (param1, param2) {
  return expression;
}
function (param1) {
  return expression;
}

Other syntax are:

// A function with no parameters requires parentheses:
() => { statements }

// Parenthesize the body to return an object literal expression:
params => ({foo: bar})

// Rest parameters and default parameters are supported
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }

Curious people click here to know detailed syntax.

#How to use?

Arrow functions are welcome to be used in place of anonymous functions.

Lets take a look.

$.ajax (url,params,(data,status) => {console.log(data);})

is equivalent to

$.ajax (url,params,function(data, status) {console.log(data)})

Another useful example.

var numbers = [16,4,9,36];

var sqrNumbers = numbers.map((number) => Math.sqrt(number));

console.log (sqrNUmbers); // [4, 2, 3, 6]

#Role of this

Theoretically every new function has its own this value. Sometime people feel its little bit frustrated because this changes its value inside inner functions and whole logic turns in another direction.

Problem Example:

function timer () {
  this.time = 0;
  setInterval(function secondBar(){
   this.time++;
   console.log (this.time);
  }, 1000);
}
var t = new timer ();

in above example, this in function secondBar() is different than timer()

personality change of this completely ruined the OO concept of using this inside the class definition.  Because of this behavior above example will print NaN after every second.

Solution Example:

Above problem can be solved by saving instance of this to some other variable and use that variable through out the function definition.

function timer () {
  var self = this;
  self.time = 0;
  setInterval(function secondBar(){
   self.time++;
   console.log (self.time);
  }, 1000);
}
var t = new timer ();

Using arrow function:

An arrow function does not create it’s own this context, rather it captures the this value of the enclosing context, so the following code works as expected.

function timer () {
  this.time = 0;
  setInterval(() => {
   this.time++;
   console.log (this.time);
  }, 1000);
}
var t = new timer ();

#Arrow function with call or apply

As stated above, arrow functions doesn’t create their own this so there is no affect of changing context using call or apply. their this will refer to enclosing scope.

lets check.

var drawingBoardUtil = {
  margin:5,
  getCircleRadius: function (radius) {
    var circle = r => r + this.margin;
    return circle(radius);
  },
  getCircleRadiusAnotherway: function (radius) {
var circle = r => r + this.margin;
var dboard = {margin:10};
return circle.call(dboard, radius);
}
}

drawingBoardUtil.getCircleRadius(5); // return 10
drawingBoardUtil.getCircleRadiusAnotherway (5); // still return 10

#arguments variable in arrow functions

 Arrow functions do not expose an arguments object to their code: arguments.length, arguments[0],arguments[1], and so forth do not refer to the arguments provided to the arrow function when called.  Instead, arguments is simply a reference to the name in the enclosing scope.

function sum(a,b) {
  var add = (a1,b1) => arguments[0] + arguments[1];//params of function sum()
  return add(a+5,b+5);
}
sum(5,6); // prints 11

// on the another hand

function sum(a,b) {
  var add = (a1,b1) => a1 + b1;//params of arrow functions
  return add(a+5,b+5);
}
sum(5,6); // prints 21

#Browser Support

Look for browser support

#Question for you

var obj = {
  value:5,
  print: () => {
   console.log (this);
   console.log (this.value);
 }
}

What will be the output? post in comment below.⇓

 

Let me know your thoughts guys.

Happy Learning!!

♥sgoyal

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s