feat(curriculum): Add interactive examples to Higher order functions lesson (#63394)

This commit is contained in:
Giftea ☕ 2025-10-31 21:25:59 +01:00 committed by GitHub
parent ac4385c932
commit 188b721b62
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -5,7 +5,7 @@ challengeType: 19
dashedName: what-are-higher-order-functions
---
# --description--
# --interactive--
Higher order functions are a powerful concept in JavaScript that can significantly enhance your coding abilities and make your code more flexible and reusable.
@ -19,6 +19,8 @@ For example, you might have a function that performs a specific operation on eac
Here's an example to illustrate this concept:
:::interactive_editor
```js
function operateOnArray(arr, operation) {
let result = [];
@ -34,13 +36,17 @@ function double(x) {
let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = operateOnArray(numbers, double);
console.log(doubledNumbers); // Outputs: [2, 4, 6, 8, 10]
console.log(doubledNumbers); // [2, 4, 6, 8, 10]
```
:::
In this example, `operateOnArray` is a higher order function. It takes an array and a function (`operation`) as arguments. It then applies the operation to each element of the array. The double function is passed as an argument to `operateOnArray`, demonstrating how functions can be used as values.
Higher order functions can also return functions. This is particularly useful for creating specialized functions based on more general ones. This concept is often referred to as function factories. Here's an example:
:::interactive_editor
```js
function multiplyBy(factor) {
return function(number) {
@ -51,10 +57,12 @@ function multiplyBy(factor) {
let double = multiplyBy(2);
let triple = multiplyBy(3);
console.log(double(5)); // Outputs: 10
console.log(triple(5)); // Outputs: 15
console.log(double(5)); // 10
console.log(triple(5)); // 15
```
:::
In this case, `multiplyBy` is a higher order function that returns a new function. This new function is specialized based on the factor passed to `multiplyBy`. This allows us to create custom multiplication functions with ease.
Higher order functions are not just a theoretical concept they're widely used in JavaScript.