Arrow functions

 

One of the most anticipated new features in the ES6 Javascript standard was the Arrow Function Expression.

It promises a shorter syntax than it's predecessor the Function Expression.


Exemple : get length of each string inside an array

let celebrities = ['Steve Jobs','Albert Einsten','Nicolas Tesla'];     

//ES5

const lengthES5 = celebrities.map(function(celebrity) {

  return celebrity.length;

});

console.log(lengthES5); //[ 10, 14, 13 ]


//ES6
const lengthES6 = celebrities.map(celebrity => {

  return celebrity.length;

});

console.log(lengthES6); //[ 10, 14, 13 ]


//ES6 much better [ 10, 14, 13 ]
celebrities.map(celebrity => celebrity.length);

 
Sandbox :
https://codesandbox.io/s/72xmrlow0j

Arrow Functions lexically bind their context so this actually refers to the originating context :


/* Function Object Context */
var sciences = ['Physics','Chemistry','Math'];
var searchedScience = 'Math';
console.log(sciences)
console.log(searchedScience)

/* ES5 Function Object Context */
//solution 1
var self = this;
this.sciences.forEach(function(science) {
    if(self.searchedScience === science){
          console.log('Founded Science 1: ', science)
    }else{
          console.log('Not Searched Science 1: ', science)
   }
});

//solution 2
this.sciences.forEach(function(science) {
   if(self.searchedScience === science){
       console.log('Founded Science 2: ', science)
   }else{
       console.log('Not Searched Science 2: ', science)
   }
}, this);

//solution 3
this.sciences.forEach(function(science) {
     if(self.searchedScience === science){
       console.log('Founded Science 3: ', science)
     }else{
       console.log('Not Searched Science 3: ', science)
    }
}.bind(this));

/* ES6 Function Object Context */
this.sciences.forEach((science) => {
   if(this.searchedScience === science){
      console.log('ES6 Founded Science: ', science)
   }else{
      console.log('ES6 Not Searched Science: ', science)
  }
});

 

js best practices

×