JavaScript Arrow Functionality

"Arrow" is the short-hand way of writing function. Before it, there was a much less-used operator in JS that would be handy way of writing "goes to" but that was not so popular as the arrow function.
  1. function countdown(n) {  
  2.   while (n --> 0)  // "n goes to zero"  
  3.     alert(n);  
  4. }  
By running this script, the 'n' value is decremented till it becomes zero. It is short hand nortation of the below code.
  1. while( (n--)>0)  
In the same way, the ==> function in JavaScript can be used to write the function.
  1. // ES5  
  2. var selected = ArrayObj.filter(function (item) {  
  3.   return item.toUpperCase()  
  4. });  
  5.   
  6. // ES6  
  7. var selected = ArrayObj.filter(item=>item.toUpperCase());  
The syntax for arrow function is  
  1. (param1, param2, …, paramN) => expression  
  2. // equivalent to: (param1, param2, …, paramN) => { return expression; }  
  3.   
  4. ()==>{return statement;} // with no parameter  
This way of notation is very useful for writing functions in making filter,s maps, or performing any operation in array object along with doing small manipulations.
  1. // An empty arrow function returns undefined  
  2. let empty = () => {};  
  3.   
  4. (() => 'foobar')();   
  5. // Returns "foobar"  
  6.   
  7.   
  8. var compareVar= a => a > 15 ? 15 : a;   
  9. compareVar(16); // 15  
  10. compareVar(10); // 10  
  11.   
  12. let max = (a, b) => a > b ? a : b;  
  13.   
  14. // Easy array filtering, mapping, ...  
  15.   
  16. var arr = [5, 6, 13, 0, 1, 18, 23];  
  17.   
  18. var sum = arr.reduce((a, b) => a + b);    
  19. // 66  
  20.   
  21. var even = arr.filter(v => v % 2 == 0);   
  22. // [6, 0, 18]  
  23.   
  24. var double = arr.map(v => v * 2);         
  25. // [10, 12, 26, 0, 2, 36, 46]  
Next time, for writting an inline function, the arrow operator can be used.
Ebook Download
View all
Learn
View all