"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.
- function countdown(n) {
- while (n --> 0) // "n goes to zero"
- alert(n);
- }
By running this script, the 'n' value is decremented till it becomes zero. It is short hand nortation of the below code.
- while( (n--)>0)
- // ES5
- var selected = ArrayObj.filter(function (item) {
- return item.toUpperCase()
- });
- // ES6
- var selected = ArrayObj.filter(item=>item.toUpperCase());
- (param1, param2, …, paramN) => expression
- // equivalent to: (param1, param2, …, paramN) => { return expression; }
- ()==>{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.
- // An empty arrow function returns undefined
- let empty = () => {};
- (() => 'foobar')();
- // Returns "foobar"
- var compareVar= a => a > 15 ? 15 : a;
- compareVar(16); // 15
- compareVar(10); // 10
- let max = (a, b) => a > b ? a : b;
- // Easy array filtering, mapping, ...
- var arr = [5, 6, 13, 0, 1, 18, 23];
- var sum = arr.reduce((a, b) => a + b);
- // 66
- var even = arr.filter(v => v % 2 == 0);
- // [6, 0, 18]
- var double = arr.map(v => v * 2);
- // [10, 12, 26, 0, 2, 36, 46]
Join the conversation! Your thoughts help the community grow.