Arrow function expressions are new syntactic sugar in ES6. Its syntax is more concise than function expressions, and not have their own this
, arguments
, super
or new.target
.
Arrow function expressions are more suitable where anonymous functions are needed, and it cannot be used as a constructor.
You should have seen the power of arrow functions in processing data.
Arrow function in a similar map()
, filter()
, reduce()
and so the need for other functions as arguments to process data in higher-order functions would be good to use.
Read the following code:
FBPosts.filter(function(post) {
return post.thumbnail !== null && post.shares > 100 && post.likes > 500;
})
We wrote down the filter
function and tried to ensure readability. Now let's write the same code with arrow functions:
FBPosts.filter((post) => post.thumbnail !== null && post.shares > 100 && post.likes > 500)
This code accomplishes the same task, but becomes shorter and easier to understand.
Now there is a sample problem: use the arrow function syntax to calculate squaredIntegers
the square of positive integers in the array (fractions are not integers).
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34];
Tip 1: You need to check the realNumberArray using filter () to obtain a positive integer (the decimal point is not an integer).
Tip 2: You need to map the value in the filter () function to the variable squaredIntegers after the map () square operation.
Tip 3: It can be called by chain.
.............................................
.............................................
.............................................
Here is the answer:
1 const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34];
2 const squareList = (arr) => {
3 "use strict";
4 const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );
5 return squaredIntegers;
6 };
7 const squaredIntegers = squareList(realNumberArray);
8 console.log(squaredIntegers);
Output result:
Part of the content is from learn.freecodecamp.one