Es6 arrow function example

Es6 arrow function example

  • 2016-08-13
  • 2557

As we have understood from Mozilla Documentation, An fat arrow function is having shorter syntax compared to traditional function expressions and binds the return value inline. These Arrow functions are always anonymous.

According to MDN, The function definition will look like:

([param] [, param]) => {
   statements
}
param => expression

Below is a quick example of Fat Arrow function as per ECMAScript 6 specification.

A short example

var a = [
  "Hydrogen",
  "Helium",
  "Lithium",
  "Beryl­lium"
];
 
var a3 = ((s) => s.length);
console.log(a3(a));

So, this function will output 4 in console. Here before => the function is not having any name and it gets the return value inline.

Below are some examples of current ECMAScript 5 functions.

How we write it in ECMA5 currently?

//1. Simple function
var str = "Please find where there is a find";
var searchStr = "find";
var pos = function(totalStr,stringToSearch){ return str.indexOf(stringToSearch) };
console.log(pos(str,searchStr));

ECMAScript 6 Equivalent

var es6pos = (totalStr,stringToSearch) => str.indexOf(stringToSearch);
console.log(es6pos(str,searchStr));

ECMAScript 5

//2. Two functions in combination
var str = "Please find where there is a find";
var searchStr = "find";
var pos = function(totalStr,stringToSearch){ return str.indexOf(stringToSearch) };
var logIt = function(anything){console.log( anything)};
logIt(pos(str,searchStr));

ECMAScript 6 Equivalent

var intermediateResult = ((totalStr,stringToSearch) => str.indexOf(stringToSearch)) ;
var es6Logit = intermediateResult => console.log( intermediateResult);
es6Logit(intermediateResult(str,searchStr));

ECMAScript 5 Foreach and For

var arr = ["a", "b", "c"];
 
arr.forEach(function(entry) {
    console.log(entry);
});
 
//old way
var index;
 
for (index = 0; index < arr.length; ++index) {
    console.log(arr[index]);
}

ECMAScript 6 Equivalent

arr.forEach(elem => console.log(elem));

ECMAScript 5 Use of this in function

function Person() {
  var self = this; 
                    
  self.age = 14;
 
  self.grow = function () {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    return self.age++;
  };
}
 
var p = new Person();
console.log(p.grow());
console.log(p.grow());

ECMAScript 6 Equivalent for Lexical this

function Person(){
  this.age = 14;
 
  this.grow = () => {
    return this.age++; // |this| properly refers to the person object
  };
}
 
var p = new Person();
 
console.log("es6 --"+ p.grow());
console.log("es6 --"+ p.grow());

Where will we implement arrow functions in a Server Side Framework like Node.js?

We can use this arrow function, where there is an inline functionality.
We should not try to use this arrow function, for global scope functions.
To have more clear code and compactness in code, we may use this Arrow function. Also we find, return value of this function will immediately have execution value in upper scope and the foreach iterator syntax will have more clarity with this function. Also as javascript introduced several utility functions like map(), reduce(), filter() etc. with arrays, this fat arrow function will have a better fit for those scenarios.

What is the Advantage of using this Feature?

As we have gone through -

  • Shorter syntax – without using function, return etc.
  • Better clarity and compact codebase for smaller inline functions
  • Get this context in all the inline functions of a class within higher order function root scope

A real interesting discussion, we have found in stackoverflow, is here.

Have we tested yet?
In Server Side – How have we tested this feature?

As of now, we do not have this => notation is not implemented yet in node.js 0.12 version. So we needed to use the harmony flag. We have use nvm (node version manager) to manage the node version.

nvm use 0.12

and then using the harmony flag:

node --harmony es6arrow.js

In Client Side – How have we tested this feature?

As of now, only Mozilla Firefox has implemented this feature.Our firefox version is 35.0.
We tested those above features in Firefox Console.

Example in Github

Code tested with node.js harmony flag

var a = [
  "Hydrogen",
  "Helium",
  "Lithium",
  "Beryl­lium"
];

var a2 = function(s){ return s.length };

var a3 = ((s) => s.length);

console.log(a2(a));
console.log(a3(a));


// Simple => 
var str = "Please find where there is a find";
var searchStr = "find";
var pos = function(totalStr,stringToSearch){ return str.indexOf(stringToSearch) };

console.log(pos(str,searchStr));

var es6pos = (totalStr,stringToSearch) => str.indexOf(stringToSearch);

console.log(es6pos(str,searchStr));

// another example  =>

var str = "Please find where there is a find";
var searchStr = "find";

var pos = function(totalStr,stringToSearch){ return str.indexOf(stringToSearch) };

var logIt = function(anything){console.log( anything)};

logIt(pos(str,searchStr));

var intermediateResult = ((totalStr,stringToSearch) => str.indexOf(stringToSearch)) ;

var es6Logit = intermediateResult => console.log(intermediateResult);

es6Logit(intermediateResult(str,searchStr));


// foreach i.e in statement body

//ecma5
var arr = ["a", "b", "c"];

arr.forEach(function(entry) {
    console.log(entry);
});

//or the old way
var index;

for (index = 0; index < arr.length; ++index) {
    console.log(arr[index]);
}

//now in es6

// Statement bodies
arr.forEach(elem => console.log(elem));

// Lexical this

//ecma5

function Person() {
  var self = this; 
                   
  self.age = 14;

  self.grow = function () {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    return self.age++;
  };
}

var p = new Person();

console.log(p.grow());
console.log(p.grow());

//ecma6

function Person(){
  this.age = 14;

  this.grow = () => {
    return this.age++; // |this| properly refers to the person object
  };
}

var p = new Person();

console.log("es6 --"+ p.grow());
console.log("es6 --"+ p.grow());

Code tested in Mozilla Firefox Console

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
  <div id ="resultLen"></div>
  <div id ="resultSearch"></div>
</body>
<script>
  var a = ["Hydrogen","Helium","Lithium","Beryl­lium"];
  var a3 = ((s) => s.length);
  var theValue = a3(a);
  console.log(theValue);
  document.getElementById('resultLen').innerHTML = theValue;
  var str = "Please find where there is a find";
  var searchStr = "find";
  var es6pos = (totalStr,stringToSearch) => str.indexOf(stringToSearch);
  theValue = es6pos(str,searchStr);
  console.log(theValue);
  document.getElementById('resultSearch').innerHTML = theValue;
  var arr = ["a", "b", "c"];
  arr.forEach(elem => console.log(elem));

  function Person(){
    this.age = 14;

    this.grow = () => {
      return this.age++; // |this| properly refers to the person object
    };
  }

  var p = new Person();

  console.log("es6 --"+ p.grow());
  console.log("es6 --"+ p.grow());

</script>
</html>

Other resources which are useful:

ECMAScript 6: A Better JavaScript for the Ambient Computing Era

JavaScript Tutorial for Absolute Beginners

Suggest

ES6 and ES7 the future of Javascript

ECMAScript 6 is Candy Sweet

JavaScript Promises: Applications in ES6 and AngularJS

Learning ECMAScript 6: Moving to the New JavaScript

ES6 Javascript Essentials (With Exercise Files)