0

Is it better to validate user input using this method

if (obj == null) {
   // detects null and undefined
   // exit the function, input not validated
}

or this method

if (!obj) {
    // detects false, 0, -0, '', null, undefined, NaN
    // exit the function, input not validated
}

In this particular case, obj represents an array to be looped through.

I'm having difficulty deciding which method to use.

employee-0
  • 917
  • 7
  • 18

2 Answers2

1

You've described the differences. So it's up to you - do you want false or '' to pass your conditional or not?

For an array, you may want to consider:

if (obj && obj.length) {
    // Your array is not null, and has items.
}
Joe Enos
  • 36,707
  • 11
  • 72
  • 128
  • @stack_temp If you're worried that `length` might give you a non-number, sure. If you go this route, and still want to validate that it's not an empty array, you'd have to go a step further with `(obj && obj.length && obj.length === +obj.length)`. You could take it another step further and ensure that the type is an array. Personally, I'd stick with simplicity - knowing that the length is "truthy" would be good enough for me. – Joe Enos Jul 23 '13 at 00:54
1

to be honest, since javascript is interpreted anyway, the overhead of the operation is huge compared to actually evaluating it, so it doesn't matter. You can always test by doing it a million times in a loop and timing which is faster.