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.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 7.69
Passing Functions as Arguments
Swipe to show menu
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.
Thanks for your feedback!