Do I need to pass empty parameters to a javascript function?
Solution 1
form_senden("abc"); is ok
the other parameters will be initialized as undefined
Solution 2
It is okay to only pass the first parameter as all other will not be set. If you want to set the 1st and 3rd argument, you will need to make the 2nd null, like so:
form_senden("a",null,"b");
Solution 3
you may do just form_senden("abc");
putting default values in the function definition.
function form_senden( form_name, cnf , confirm_txt , trigger_field , ,do_check , chknfcs, allow, errorMsg ){
if(typeof(cnf)==='undefined') cnf = '';
if(typeof(confirm_txt)==='undefined') confirm_txt = ''; ...and so on
// do something
}
Solution 4
if you have something like:
const myFunc = (a = 1, b = 2, c = 3) => a + b + c;
if you call myFunc();
you will get 6.
but if you for example wants to call myFunc with c = 4 and let a and b at its default values, you can call myFunc like this:
myFunc(undefined, undefined, 4);
and this will return 7.
Solution 5
Omitting function parameters is okay, the missing parameters will have undefined
value in the function.
Related videos on Youtube
frequent
Updated on February 28, 2020Comments
-
frequent about 4 years
Say I have a function like this, which i'm calling throughout a script:
function form_senden( form_name, cnf, confirm_txt, trigger_field, ,do_check, chknfcs, allow, errorMsg ){ // do something }
On most of my function calls, I'm only passing the first parameter.
Question:
Is it ok in this case to omit passing empty parameters like so:form_senden("abc");
Or do I need to pass all parameters regardless if they are used like so:
form_senden("abc","","","","","","","","");
Thanks!
-
mu is too short over 11 yearsI'd recommend using an options object for the parameters if you have that many:
form_senden({ form_name: '...', cnf: '...')
orform_senden(form_name, { confirm_txt: '...', allow: true })
. -
frequent over 11 yearsand then I only pass the options that I want?
-
mu is too short over 11 yearsRight, a large number of positional parameters is a (bad) code smell, especially when most of them are optional. You'll be glad you did this six months down the road when you have to figure out this code again.
-
-
jmav over 11 yearsSimple form for defining default value: cnf = cnf || 'default value';
-
Ivan Durst almost 9 yearsThis is the answer I was looking for, and is more complete than the selected answer. +1
-
HussienK almost 8 yearsIs there a way I can be more explicit with passing optional arguments? In python you can do something like this form_senden("a", cnf=None, "b"). Can you do something similar to this in JavaScript?
-
Gung Foo almost 8 yearsNot natively - but you can wrap your parameters into an object and hand that to the function.
-
Jonathan almost 4 yearsundefined, not null, is the only possibility according to tslint
-
cliffclof over 2 yearsDoes JS allow myFunc( , , 4); Or myFunc( 3, , 4); ??