Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing in function parameters that don't exist or are undefined? [duplicate]

Tags:

javascript

I was wondering what the best practice would if I had function that accepted 4 params a,b,c,d but I had a situation where I didnt have a value to pass in for param c but needed to pass in a value for param d so:

function myFunction(a,b,c,d) {
 //...
}

myFunction(paramA, paramB, '', paramD);

do you pass in undefined for param c and then do a check inside the function or something like that?

like image 733
styler Avatar asked Feb 17 '23 06:02

styler


1 Answers

Better is to use Object for me:

function myFunction( options ) {
 //...
}

myFunction({
    paramA: "someVal",
    paramD: "anotherVal"
});

Then in function you can check for empty params and pass defaults:

function myFunction( options ) {
    options = options || {};
    options.paramA = options.paramA || "defaultValue";
    // etc...
}    
like image 53
antyrat Avatar answered Feb 18 '23 20:02

antyrat