In our previous JavaScript tutorial, we had discussed the basic concepts of functions in JavaScript. We learned ways of defining them, calling them by their names, passing some parameters into a function, and returning some values from a function. Moving forward in our study of functions, let us get started with the anonymous function, followed respectively by an arrow function and then a higher-order function. When one is writing modern JavaScript, these tools become quite important due to their ability to make your code more verbose and visually appealing.
Anonymous Functions
Anonymous functions-functions that have no names-are mainly used for function expressions or as arguments of other functions. They come in useful in cases where the function only needs to be created temporarily, as in the case of event handling or doing a simple one-time action.
Example of Anonymous Function
The assignment of an anonymous function, to a variable:
let show = function() {
console.log("This is an example of an anonymous function!");
};
show();
Arrow Functions
Arrow functions were introduced with ES6. That is it requires writing functions in compact syntax. Although arrow functions offer very compact syntax, creation of arrow functions doesn’t bind this value. That makes them perfect for handling situations where the context this would be used:
Example of Arrow Functions
This is the basic syntax of an arrow function.
const add = (a, b) => a + b;
console.log(add(5, 3)); // Output: 8
Arrow functions can also be used for cases that include multiple statements, where you need to enclose these statements in curly braces and explicitly return a value:
const multiply = (a, b) => {
let result = a * b;
return result;
};
console.log(multiply(4, 3)); // Output: 12
Higher-Order Functions
Higher-order functions are those functions that accept other functions as arguments or return functions. They are very good abstract building blocks, and they are utilized to construct flexible and reusable pieces of code.
Example of Higher-Order Functions
The methods for sorting, searching and manipulating all elements of a collection use the higher order functions. The Array.prototype.map which is one of the daily use cases of higher-order functions lets you execute a function using every element in the array returning a new array.
const numbers = [1, 2, 3, 4];
const squares = numbers.map(x => x * x);
console.log(squares); // Output: [1, 4, 9, 16]
Summary
Finally, by learning how to use anonymous, arrow, and higher order functions, you will be able to write more concise, descriptive, and reusable JavaScript code. All these higher order function techniques you’ll have at your disposal will give you more flexibility and power when it comes to solving more complex problems.
We really hope you’ve learned something very valuable today. See you in the next lesson where we’re going to continue exploring the amazingly powerful features of JavaScript!