Day 5: Arrow Functions
Arrow Functions in JavaScript
Arrow Functions
These expressions lexically bind the this
value while using less syntax than a typical function expression. Arrow functions are always anonymous.
Here are some basic examples of arrow function syntax:
(parameter) => {statements}
parameter => {statements}
parameter => expression
parameter => {return expression}
(param1, param2, ..., paramN) => {statements}
(param1, param2, ..., paramN) => expression
(param1, param2, ..., paramN) => {return expression}
Let's look at some simple ways to apply this syntax:
'use strict';
const makeArray = (values) => { return values };
console.log('Array:', makeArray(1, 2, 3, 4));
console.log('Array:', makeArray(1, 2, 3, 4, 5, 6));
const getSum = (a, b) => { return a + b };
console.log('1 + 2 =', getSum(1, 2));
const greeting = 'Hello, World.';
const capitalize = (myString) => { return myString.toUpperCase() };
console.log(greeting, '=>', capitalize(greeting));
Using Arrow Functions
Let's look at some ways we can use arrow functions to make our code shorter.
Sum the Elements of an Array
While we can certainly iterate over an array and sum each value, we can also use the reduce function.
'use strict';
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce(function (a, b) {
return a + b;
}, 0);
console.log('Array:', arr);
console.log('Sum:', sum);
Now, let's reduce the length of our code using an arrow function:
'use strict';
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((a, b) => { return a + b }, 0);
console.log('Array:', arr);
console.log('Sum:', sum);
Let's further reduce it by getting rid of the return
:
'use strict';
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((a, b) => a + b, 0);
console.log('Array:', arr);
console.log('Sum:', sum);
Find the Length of Strings in an Array
Let's take an array of strings and use it to create a new array containing the respective lengths of its elements.
'use strict';
const arr = ['first', 'second', 'third', 'fourth', 'fifth'];
const len = arr.map(function(s) { return s.length });
console.log('Array:', arr);
console.log('Lengths:', len);
Now, let's reduce the length of our code using an arrow function:
'use strict';
const arr = ['first', 'second', 'third', 'fourth', 'fifth'];
const len = arr.map(s => s.length);
console.log('Array:', arr);
console.log('Lengths:', len);
Find Array Elements Greater Than a Value
Let's find all the elements in an array that are greater than and add them to a new array.
'use strict';
const arr = [1, 2, 3, 4, 5];
const greaterThan3 = arr.filter(function(a) {
return a > 3;
});
console.log('Array:', arr);
console.log('Elements Greater Than 3:', greaterThan3);
Now, let's reduce the length of our code using an arrow function:
'use strict';
const arr = [1, 2, 3, 4, 5];
const greaterThan3 = arr.filter(a => a > 3);
console.log('Array:', arr);
console.log('Elements Greater Than 3:', greaterThan3);
Table Of Contents