Duvdevan Duvdevan - 24 days ago 8
Javascript Question

How to check if argument is defined in function definition in JavaScript?

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?

Answer

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

Comments