How to check if argument is defined in function definition in JavaScript? -
for example if have function defined this:
function set_name(name) { return name; } but call way (for personal reasons way):
set_name.apply(this, ['duvdevan', 'omerowitz']); what best practice check , prevent set_name function's further execution if had accepted more 1 parameter / argument?
also, have note i'm trying figure out way check before call .apply function:
function set_name(name) { // if(arguments.length > 1) console.log('this not need though.'); return name; } var args = ['duvdevan', 'omerowitz']; // now, @ point i'd check if set_name function can accept 2 arguments. // if not, i'd console.log or return new error here. set_name.apply(this, args); is doable?
you can number of arguments expected 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
Post a Comment