Introduction
In this lab, we will explore the implementation of a JavaScript function called nthArg, which allows us to retrieve the nth argument of a function. We will learn how to use Array.prototype.slice() method to retrieve the desired argument, and also how to handle negative values for n. By the end of this lab, we will have a solid understanding of how to use nthArg to retrieve arguments from a function.
A function that gets the nth argument
To start practicing coding, open the Terminal/SSH and type node. Here's how you can create a function that gets the argument at index n.
- Use
Array.prototype.slice()to get the desired argument at indexn. - If
nis negative, the nth argument from the end is returned.
const nthArg =
(n) =>
(...args) =>
args.slice(n)[0];
Here's an example of how to use the nthArg function:
const third = nthArg(2);
console.log(third(1, 2, 3)); // Output: 3
console.log(third(1, 2)); // Output: undefined
const last = nthArg(-1);
console.log(last(1, 2, 3, 4, 5)); // Output: 5
Summary
Congratulations! You have completed the NTH Argument lab. You can practice more labs in LabEx to improve your skills.