Passing Functions as Arguments
In JavaScript, functions are not just blocks of code—they are values that you can pass around, store in variables, and even give as arguments to other functions. This powerful idea leads to what are called higher-order functions: functions that take other functions as parameters or return them as results.
When you pass a function as an argument to another function, the passed-in function is known as a callback. Callbacks are a core concept in JavaScript, allowing you to write flexible, reusable code that can handle a wide range of behaviors.
123456789101112131415function processArray(arr, callback) { const result = []; for (let i = 0; i < arr.length; i++) { result.push(callback(arr[i])); } return result; } const numbers = [1, 2, 3, 4]; function double(x) { return x * 2; } const doubled = processArray(numbers, double); console.log(doubled); // Output: [2, 4, 6, 8]
You will encounter callbacks throughout JavaScript, especially in situations where you want to customize behavior. Some of the most common real-world uses for callbacks include:
- Event handling, where you provide a function to run when a user clicks a button;
- Timers, where you pass a function to be executed after a delay;
- Array helpers, such as
map,filter, andforEach, which all take functions as arguments to determine what to do with each item in an array.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Awesome!
Completion rate improved to 7.69
Passing Functions as Arguments
Veeg om het menu te tonen
In JavaScript, functions are not just blocks of code—they are values that you can pass around, store in variables, and even give as arguments to other functions. This powerful idea leads to what are called higher-order functions: functions that take other functions as parameters or return them as results.
When you pass a function as an argument to another function, the passed-in function is known as a callback. Callbacks are a core concept in JavaScript, allowing you to write flexible, reusable code that can handle a wide range of behaviors.
123456789101112131415function processArray(arr, callback) { const result = []; for (let i = 0; i < arr.length; i++) { result.push(callback(arr[i])); } return result; } const numbers = [1, 2, 3, 4]; function double(x) { return x * 2; } const doubled = processArray(numbers, double); console.log(doubled); // Output: [2, 4, 6, 8]
You will encounter callbacks throughout JavaScript, especially in situations where you want to customize behavior. Some of the most common real-world uses for callbacks include:
- Event handling, where you provide a function to run when a user clicks a button;
- Timers, where you pass a function to be executed after a delay;
- Array helpers, such as
map,filter, andforEach, which all take functions as arguments to determine what to do with each item in an array.
Bedankt voor je feedback!