Function literals are useful with higher order functions where function parameters are required. Often, this is helpful with filter, map, and reduce. It is especially nice if we only need to use that function once and we aren't planning on reusing the same logic again. Instead of defining a separate function then passing the name of this function as our argument, we just pass the logic directly. Function literals are also called anonymous functions or lambdas.
Here's an example with lists and the filter function that does NOT use function literals:
import { listify } from "introcs/list";
let a: Node<number> = listify(1, 12, 123, 1.234);
let greaterThan10 = (n: number): boolean => {
return n > 10;
};
let b: Node<number> = filter(a, greaterThan10);
// b is the list 12->123->null
Here's the same example using function literals:
import { listify } from "introcs/list";
let a: Node<number> = listify(1, 12, 123, 1.234);
let b: Node<number> = filter(a, (n: number): boolean => {
return n > 10;
});
// b is the list 12->123->null
In this last version of the example, we just plugged the function right in as our argument, and we still got the same result as in the previous version when we stored it as greaterThan10 and passed in greaterThan10 as the argument. Here we used it with filter, but it's also nice with map and reduce.
When using a function literal as part of a higher order function, we can rely on type inference for the function literal's parameter types and return type. Since we can do this, we can go ahead and remove type declarations when we use function literals in this way. Here's how this would look with the previous example (and we'll rely on type inference when declaring a and b too):
import { listify } from "introcs/list";
let a = listify(1, 12, 123, 1.234);
let b = filter(a, (n) => {
return n > 10;
});
// took out the parameter type which would normally go after the n
// took out return type normally before the =>
print(b); // prints the list 12->123->null
When a function literal's body is only one return statement, we can condense it using a shorthand notation. To do this, follow these steps:
Here's what this becomes in our example:
import { listify } from "introcs";
let a = listify(1, 12, 123, 1.234);
let b = filter(a, (n) => n > 10);
// b is the list 12->123->null