2

For example if I have a function defined like this:

function set_name(name) {
    return name;
}

But I call it this way (for personal reasons this way):

set_name.apply(this, ['Duvdevan', 'Omerowitz']);

What would be the best practice to check and prevent set_name function's further execution if it had accepted more than 1 parameter / argument?

Also, I have to note that I'm trying to figure out a way to check this before I call .apply function:

function set_name(name) {
    // if(arguments.length > 1) console.log('This is not what I need though.');

    return name;
}

var args = ['Duvdevan', 'Omerowitz'];

// Now, at this point I'd like to check if the set_name function can accept two arguments.
// If not, I'd console.log or return new Error here.

set_name.apply(this, args);

Is this doable?

1
  • So if it has more than one argument, you want it to not run? Only way would be the if like you coded it... Commented Nov 10, 2016 at 21:57

1 Answer 1

3

You can get the number of arguments expected by the function via Function.length:

function set_name(name) {
  return name;
}

var args = ['Duvdevan', 'Omerowitz'];

console.log(set_name.length);         // 1

if (args.length > set_name.length) {
  throw new Error('Too many values'); // throws
}

set_name.apply(this, args);           // not executed

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

1 Comment

Pretty damn awesome! Actually, I was afraid that I'd have to do set_name.toString() and parse the actually function definition for defined arguments ... but this, you're a JavaScript Gandalf! Thanks!

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.