2

When I'm writing utility functions, I'll often check for the existence of required arguments so I can return something other than the intended value if it's missing. I typically return null or undefined, and then I'll check that value where I'm using it.

For example:

function utility(arg1, arg2) {
  if (!(arg a&& arg2)) {
    return null;
  }
  // ... other code
}


var foo = utility(one, two);

if (foo) {
  // .. so on
}

Because null and undefined and false will return falsey when tested for truth, my questions are:

  • Is there a benefit or best practice of returning one over the other? Or is it simply personal preference or maintaining consistency in a code base?
  • Are there edge cases I'm not thinking of or haven't come across?
Ben
  • 5,283
  • 9
  • 35
  • 44
  • Yes, when returned result is compared. And when returning from event handler – Tushar Apr 08 '16 at 15:33
  • 5
    Have you considered throwing an exception when ***required*** arguments aren't provided? Or is "returning a meaningless value" considered acceptable and normal behaviour for that function? – deceze Apr 08 '16 at 15:34
  • If you have a Boolean function, returning null or undefined when the arguments are missing or unacceptable would be more clear, as long as you use "===". – TecBrat Apr 08 '16 at 15:36
  • 1
    Possible duplicate of [What is the difference between null and undefined in JavaScript?](http://stackoverflow.com/questions/5076944/what-is-the-difference-between-null-and-undefined-in-javascript) – AKS Apr 08 '16 at 15:36
  • 1
    that should read "will return false**y**". Falsey and truethy are different than `false` and `true`. Also, `0` is considered falsey in javascript. Most of the time, you'll want to check explicitly against `false` to avoid inadvertently executing fail logic against a valid value (e.g. `0`) where the return is actually valid. You could check against `null` or `undefined` and have your function return those instead, but that's not really conventional use of those values. – Joseph Marikle Apr 08 '16 at 15:37
  • @deceze that's a good point, I haven't considered that (I'm a bit uneducated about best practices of throwing errors), but it sounds like that could possibly be what I was getting at, as missing arguments (in certain cases like the one I'm working on now) for my utility function shouldn't be acceptable and is only user error. – Ben Apr 08 '16 at 15:48

0 Answers0