Introduction
In this lab, we will explore how to use the partialRight() function in JavaScript to create new functions with pre-specified arguments. This powerful function allows us to easily append arguments to existing functions, enabling us to create new functions with specific behaviors without having to redefine the original function. We'll see examples of how to use partialRight() to streamline our code and make it more modular.
Function that Appends Arguments
To create a function that appends arguments to the ones it receives, follow these steps:
- Open the Terminal/SSH and type
nodeto start coding practice. - Use the spread operator (
...) to appendpartialsto the list of arguments offn. - Use the following code to create the function:
const partialRight =
(fn, ...partials) =>
(...args) =>
fn(...args, ...partials);
- Test the function with an example, such as:
const greet = (greeting, name) => greeting + " " + name + "!";
const greetJohn = partialRight(greet, "John");
greetJohn("Hello"); // 'Hello John!'
Summary
Congratulations! You have completed the Append Function Arguments lab. You can practice more labs in LabEx to improve your skills.