Shivangi Rajde
How can you pass n arguments in any JavaScript function?
By Shivangi Rajde in JavaScript on Jun 08 2023
  • Shivangi Rajde
    Jun, 2023 9

    In JavaScript, you can pass any number of arguments to a function using the arguments object or by using the rest parameter syntax.

    Using the arguments object:

    1. The arguments object is an array-like object that contains all the arguments passed to a function.
    1. function myFunction() {
    2. for (let i = 0; i < arguments.length; i++) {
    3. console.log(arguments[i]);
    4. }
    5. }
    6. myFunction('arg1', 'arg2', 'arg3');

    In this example, the myFunction function can accept any number of arguments. Inside the function, you can access the arguments using the arguments object. It allows you to iterate over the arguments using a loop and access them by index.

    1. Using the rest parameter syntax:
      The rest parameter syntax allows you to represent an indefinite number of arguments as an array.
    1. function myFunction(...args) {
    2. for (let i = 0; i < args.length; i++) {
    3. console.log(args[i]);
    4. }
    5. }
    6. myFunction('arg1', 'arg2', 'arg3');

    In this example, the myFunction function uses the rest parameter syntax (…args) to capture any number of arguments into an array named args. You can then iterate over the args array and access the individual arguments.

    Both approaches allow you to pass any number of arguments to a function in JavaScript. Choose the one that suits your use case and coding style.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS