Passing parameters to functions that do not exist or are undefined?

I was wondering what would be better if I had a function that took 4 parameters a, b, c, d, but I had a situation where I did not have a value to pass for param c, but to pass a value to param d so:

function myFunction(a,b,c,d) { //... } myFunction(paramA, paramB, '', paramD); 

Do you pass undefined for the parameter c, and then do a check inside the function or something like that?

+4
source share
5 answers

Better use Object for me:

 function myFunction( options ) { //... } myFunction({ paramA: "someVal", paramD: "anotherVal" }); 

Then in the function you can check for empty parameters and pass default values:

 function myFunction( options ) { options = options || {}; options.paramA = options.paramA || "defaultValue"; // etc... } 
+6
source

You can make any optional parameters farther to the right of your function signature, so you can just leave them when you call the function.

 function myFunction(a, b, d, c) { // ... } myFunction(1, 2, 3, 4); // call without 'c' myFunction(1, 2, 3); 
+1
source

I will find setting the default if it is undefined is the most symplectic / reliable solution

 function myFunction(a,b,c,d) { if (typeof a === 'undefined') { a = 'val'; } if (typeof b === 'undefined') { b = 'val'; } if (typeof c === 'undefined') { c = 'val'; } if (typeof d === 'undefined') { d = 'val'; } } 
+1
source

Pass null as a parameter that you don't have. undefined bit more specialized, although they will work the same way.

0
source

If you know which parameter was passed, you can use the parameter "arguments" to the function. For instance:

  function example(a, b, c, d) { if (arguments.length < 4) { paramC = defaultParam; // something default value for passed C } } 
0
source

Source: https://habr.com/ru/post/1485613/


All Articles