4

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.

1

1 Answer 1

8

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; }

Sign up to request clarification or add additional context in comments.

2 Comments

You're right - I changed back to checking arguments and now I'm not getting these errors. I'm not sure what happened. I think I may have confused errors related to a use of arguments.callee with errors because of arguments.length.
callee.callee is in strict mode not supported -> developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.