this post was submitted on 15 Oct 2024
10 points (100.0% liked)

JavaScript

1700 readers
3 users here now

founded 2 years ago
MODERATORS
 

Should I create functions/methods for packages/libraries that allow optional parameters to accept null?

In this example below, I set the 3rd and 4th parameter as null which will act as the default value.

myLibrary.myFunction(1, 7, null, null, true);

Or is this not a good way to go about creating functions for a package and therefore should not accept null as a parameter value.

myLibrary.myFunction(1, 7, false, 4, true);
you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 2 points 1 month ago* (last edited 1 month ago)

Having to pass in null values seems a bit weird. You can define functions and optional parameters like this:

function myFunction(a = 1, b = 1, c = null, d = null, e = true) {
  return a * b;
}

Then people don't have to call your function with

myLibrary.myFunction(1, 7, null, null, true);

they just call your library with

myLibrary.myFunction(1, 7);

You could add a default inside the method signature, like:

function myFunction(a = 1, b = 1, c = null, d = null, e = true) {
  if (c === null) {
    c = 5;
  }
  return a * b * c;
}

because if you define it in the method:

function myFunction(a = 1, b = 1, c = 5, d = null, e = true) {
  return a * b * c;
}

then if people still call it with

console.log(myFunction(5, 2, null));

Then the default c = 5 is overwritten by null, and results in 0.

I don't know if you really need to handle all that though, instead of just doing c = 5 - if people intentionally call your library with null, and things go wrong...? well yea ok, don't do that then.

But it depends on the use-case. If this is some method deep within a library, and some other calling method might be unintentionally dumping null into it, you could default it inside the method, and handle it