Implict Return
In JavaScript, an implicit return undefined occurs when the return statement is omitted from a function. The word implicit in this context refers to something that is implied but not directly stated. In other words, there was no return undefined as it would result in undefined.
Example:
const sum = (a, b) => {
a + b;
}
sum(2, 5); // undefined
In the above example, sum(2,5) returns undefined because we don't have the return keyword in the function body.
Example:
// implicit return
const sum = (a, b) => a + b;
sum(2, 5); // 7
The return keyword and curly braces are not necessary if your arrow function is only one line long.
//without implicit return
const canVote = age => {
return age >= 18;
}
Let's utilize implicit return by:
removing the curly braces
removing the
returnkeyword
const canVote = age => age >= 18;
This is the clearest and shortest approach to write this function.
Array Methods Using Implicit Returns
Now let's see how to create the callback using arrow functions and implicit returns.
Array.filter()
//without implicit return
const ages = [10, 15, 21 45];
const agesAboveTwentyOne = ages.filter(function(age) {
return age > 21;
});
console.log(agesAboveTwentyOne); //[21, 45]
//with implicit return
const agesAboveTwentyOne = ages.filter(age => age > 21);
We filter the ages where the age is bigger than 21.
Array.find()
//without implicit return
const furBabies = ['Dutches', 'Monty', 'Benny', 'Lucky', 'Chili'];
const findNames = furBabies.find(function(furBaby) {
return furBaby === 'Benny';
});
console.log(findNames); // 'Benny'
//with implicit return
const findNames = furBabies.find(furBaby => furBaby === 'Benny');
From the furBabies array, find the furBaby that is equal to the string 'Benny'.
Array.map()
//Without implicit return
const numbers = [2, 6, 8, 10];
const tripled = numbers.map(function(number){
return number * 3;
});
console.log(tripled); //[6, 18, 24, 30]
//with implicit return
const tripled = numbers.map(number => number *3);
Create a new array based on the numbers array, where every number is multiplied by 3.

Top comments (0)