Retrieve Function Arguments with nthArg

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/ToolsandEnvironmentGroup(["`Tools and Environment`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") javascript/ToolsandEnvironmentGroup -.-> javascript/debugging("`Debugging`") subgraph Lab Skills javascript/variables -.-> lab-28512{{"`Retrieve Function Arguments with nthArg`"}} javascript/data_types -.-> lab-28512{{"`Retrieve Function Arguments with nthArg`"}} javascript/arith_ops -.-> lab-28512{{"`Retrieve Function Arguments with nthArg`"}} javascript/comp_ops -.-> lab-28512{{"`Retrieve Function Arguments with nthArg`"}} javascript/spread_rest -.-> lab-28512{{"`Retrieve Function Arguments with nthArg`"}} javascript/debugging -.-> lab-28512{{"`Retrieve Function Arguments with nthArg`"}} end

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 index n.
  • If n is 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.

Other JavaScript Tutorials you may like