Ad space (banner)
🟨JavaScript Lessons
Lesson 30 / 69

Higher-Order Functions (Passing a Function as an Argument)

In this lesson you'll learn the idea of higher-order functions in JavaScript so you can write flexible code that passes functions as arguments. This is for people searching "JavaScript what is a higher-order function" or "JavaScript sort comparator."

Being able to pass one function as an argument to another is called a higher-order function. Picture it like: "specify only the method of doing the work, and let the other party actually do it." Passing a comparison rule to .sort() is a classic example. In fact, .map() and .filter(), which you've already learned, are also a kind of higher-order function that receives a function as an argument.

The sample code defines a comparison function called byDescending and passes it as an argument to .sort(), as in nums.sort(byDescending). The sort order is decided by whether the comparison function returns a positive or negative value — just by rewriting this one function, you can freely switch between ascending and descending order.

A common beginner stumbling block is that using .sort() without a comparison function compares even numbers as strings, producing an unintended order. [10, 2, 1].sort() ends up sorted in string order rather than numeric order, so you must always pass a comparison function to sort numbers correctly.

In real development, the idea of a higher-order function is useful when building a list screen where users can choose the sort criteria (by price, by newest, etc.). It's a very important idea underpinning modern JavaScript style.

The idea of passing a callback function is also used in common across event handling (what happens when a button is clicked) and async code — an important concept you can't avoid when it comes to understanding JavaScript.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)