Advertisement:
Read Later
In ES6, JavaScript Arrow Functions give developers a new way to make expressions especially when using higher-order functions such as filter, map, reduce and sort. By implementing arrow functions on your script, you can code shorter and elegant as compared to writing a whole return function embedded in a higher-order function.
Syntax(1)
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }
// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }
// The parameter list for a function with no parameters should be written with a pair of parentheses.
() => { statements }
// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})
// Rest parameters and default parameters are supported
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }
// Destructuring within the parameter list is also supported
var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f(); // 6
Create a multi array containing user objects, named user.
1 - ) Filter users who have premium accounts.
2 - ) Map users depending on the length of their names.
3 - ) Sort users by payment variable.
4 - ) Get the total payment and average monthly payment by using reduce().
var user = [
{firstname: "John", lastname: "Doe", type: "Premium", payment: 350},
{firstname: "Jane", lastname: "Doe", type: "Premium", payment: 250},
{firstname: "Michael", lastname: "Undefined", type: "Free", payment: 0},
{firstname: "Undefined", lastname: "Jennifer", type: "Premium", payment: 650},
{firstname: "Chris", lastname: "Undefined", type: "Free", payment: 0},
{firstname: "Steve", lastname: "Rogers", type: "Premium", payment: 1500}
];
// Filter users who have premium accounts.
const getPremium = user.filter(premium => premium.type === "Premium");
console.log("Premium = ");
console.log(getPremium);
// Map users depending on the length of their names.
const getLength = user.map(person => person.firstname.length);
console.log("Length = ");
console.log(getLength);
// Sort users by payment variable.
const Payment = user.sort((u1, u2) => (u1.payment < u2.payment ? 1 : -1));
console.log("Payment = ");
console.log(Payment);
// Get the total payment and average monthly payment by using reduce().
const PaymentSum = user.reduce((sum, p) => (sum + p.payment), 0);
console.log("Payment Sum = ");
console.log(PaymentSum);
console.log("Average Monthly Payment = ");
console.log(PaymentSum / 12);
Result:
To inspect results, open your browser's console log and find these lines below.
[ Control + Shift + J ]
1 - ) Premium =
2 - ) Length =
3 - ) Payment =
4 - ) Payment Sum = and Average Monthly Payment =
(1)https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions