javascriptalgorithmfunctionargumentsmarshalling

Is it possible to get all arguments of a function as single object inside that function?


In PHP there is func_num_args and func_get_args, is there something similar for JavaScript?


Solution

  • For modern Javascript or Typescript:

    class Foo {
        reallyCoolMethodISwear(...args) { return args.length; }
    }
    
    function reallyCoolFunction(i, ...args) { return args[i]; }
    
    const allHailTheLambda = (...args) => {
        return args.constructor == Array;
    };
    
    const x = new Foo().reallyCoolMethodISwear(0, 1, 2, 3, 4);
    const y = reallyCoolFunction(3, 0, 1, 2, 3, 4, 5, 6);
    const z = allHailTheLambda(43110, "world");
    
    console.log(x, y, z); // 5 3 true
    

    For ancient Javascript:

    Use arguments. You can access it like an array. Use arguments.length for the number of arguments.