0

I thought I was clever by writing code that did this:

someFunction = (arg1, arg2, arg3) ->
  if _.some(arguments, (a) -> a is undefined)
    throw new Error "undefined parameter"

My intent is that if one of the parameters is undefined, throw an error. But I just discovered it doesn't always work: If someone does not pass in a parameter at all, it's not included in the arguments array and therefore it doesn't get checked.

Is there an easy way to throw an error if this function is called like someFunction(1, 2) or someFunction(1) without checking every parameter by hand?

0

2 Answers 2

2

Use arguments.length

function doSomething(arg1,arg2,arg3){
    if(arguments.length!=3){
          throw new Error("wrong param count");
    }

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

Comments

1

You could check arguments.length.

function someFunction(arg1, arg2, arg3) {
    if (arguments.length !== 3) throw new Error('undefined parameter');
}

Comments

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.