javascriptargumentsstrictuse-strict

How to count the number of arguments to a JavaScript function without using "arguments"?


I've been updating a library I wrote some time ago, and in doing so have realized that there are unexpected errors when testing in strict mode. These arise because of checks at the beginning of some of the API functions which throw an error if there is an incorrect number of arguments. Here's an example:

if(arguments.length < 2){
    throw new Error("Function requires at least two arguments.");
}

The second argument may be absolutely any value, so checking for null/undefined does not indicate whether the argument is missing or invalid. However, if the argument is missing, then there has absolutely been an error in usage. I would like to report this as a thrown Error if at all possible.

Unfortunately, the arguments object is inaccessible in strict mode. Attempting to access it in that code snippet above produces an error.

How can I perform a similar check in strict mode, without access to the arguments object?

Edit: Nina Scholz has erroneously marked this question as a duplicate.


Solution

  • You could check the length of the expected arguments (Function#length) and check against the given arguments (arguments.length).

    This works in 'strict mode' as well.

    'use strict';
    
    function foo(a, b) {
        console.log('function length:', foo.length);
        console.log('argument length:', arguments.length);
        console.log('values:', a, b)
    }
    
    foo();
    foo(1);
    foo(1, 2);
    foo(1, 2, 3);
    .as-console-wrapper { max-height: 100% !important; top: 0; }