Converting a traditional function to an arrow function
If you're old like me (in my 40s) and got into JavaScript way before ES6 (2015) but didn't use the new syntax that came out post 2015 like arrow functions, then here's a preview of how to convert traditional functions to arrow functions - as an argument to a ES6 functions like find
, map
, filter
and reduce
.
const arr = [3, 5, 6, 8, 7];
console.log("=== Array ===");
console.log(arr);
console.log("");
// Find - will return 6
let es6_find_1 = arr.find(function(n)
{
if (n % 2 === 0)
{
return true;
}
return false;
});
let es6_find_2 = arr.find(n => n % 2 === 0);
console.log("=== Find ===");
console.log(es6_find_1);
console.log(es6_find_2);
console.log("");
// Map - will return [ 6, 10, 12, 16, 14 ]
let es6_map_1 = arr.map(function(n)
{
return n * 2;
});
let es6_map_2 = arr.map(n => n * 2);
console.log("=== Map ===");
console.log(es6_map_1);
console.log(es6_map_2);
console.log("");
// Filter - will return [ 6, 8 ]
let es6_filter_1 = arr.filter(function(n)
{
if (n % 2 === 0)
{
return true;
}
return false;
});
let es6_filter_2 = arr.filter(n => n % 2 === 0);
console.log("=== Filter ===");
console.log(es6_filter_1);
console.log(es6_filter_2);
console.log("");
// Reduce - will return 29
let es6_reduce_1 = arr.reduce(function(acc, cur)
{
return acc + cur;
});
let es6_reduce_2 = arr.reduce((acc, cur) => acc + cur);
console.log("=== Reduce ===");
console.log(es6_reduce_1);
console.log(es6_reduce_2);
console.log("");