How to invoke a function with its arguments transformed in JavaScript?


In JavaScript, we can create functions that take other functions as arguments and invoke them with transformed arguments. This is a powerful technique that can be used to create higher−order functions, which can take a function and return a new function with different behavior.

What are Transforming Function Arguments

To transform function arguments, we can use the built−in methods map() and reduce(). These methods can be used on arrays to transform the elements in the array. We can use them on functions to transform the arguments that are passed to the function.

The map() Method

The map() method takes a function and an array as arguments. It invokes the function with each element in the array, and returns a new array with the transformed elements.

For example, let's say we have an array of numbers and we want to square each element in the array. We can use the map() method and an anonymous function to do this−

<!doctype html> <html> <head> <title>Examples</title> </head> <body> <div id="result"></div> <script> var numbers = [1, 2, 3, 4, 5]; var squared = numbers.map(function(number) { return number * number; }); document.getElementById("result").innerHTML = squared </script> </body> </html>

In the above code, we have an array of numbers and we use the map() method to square each element in the array. The map() method invokes the function that we provide with each element in the array, and returns a new array with the transformed elements.

The reduce() Method

The reduce() method takes a function and an array as arguments. It invokes the function with each element in the array, and returns a single value that is the result of the function.

For example, let's say we have an array of numbers and we want to add them all together. We can use the reduce() method and an anonymous function to do this−

<!doctype html> <html> <head> <title>Examples</title> </head> <body> <div id="result"></div> <script> var numbers = [1, 2, 3, 4, 5]; var sum = numbers.reduce(function(a, b) { return a + b; }); document.getElementById("result").innerHTML = sum </script> </body> </html>

In the above code, we have an array of numbers and we use the reduce() method to add them all together. The reduce() method invokes the function that we provide with each element in the array, and returns a single value that is the result of the function.

In JavaScript, we can create functions that take other functions as arguments and invoke them with transformed arguments. This is a powerful technique that can be used to create higher−order functions.

Updated on: 14-Sep-2022

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements