0

Underscore.js has two methods _.isNull and _.isUndefined which we use a lot in our code and we've also created a mix-in for _.isUndefinedOrNull.

I recently realised that I could easily use javascripts "truthiness" to achieve the same results most of the time so the question is, is that considered bad practice?

What's better?

if(someVariable){...}

or

if(_.isNull(someVariable) || _.isUndefined(someVariable){...}
BenCr
  • 5,991
  • 5
  • 44
  • 68

2 Answers2

3

They both are entirely different.

if (someVariable)

will evaluate to falsy, if someVariable is 0 or false. So it is better to have explicit checks in this case. You might like to check the truth table in this answer which shows when a variable will be evaluated to either truthy or falsy.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

I recently realised that I could easily use javascripts "truthiness" to achieve the same results most of the time

If only most of the time, then your solution doesn't work. Use if (someVariable == null) instead to test for either undefined or null.

so the question is, is that considered bad practice?

Not necessarily. If you know that all the possible values for someVariable other than the null/undefined you want to test for are truthy (e.g. objects), then it's fine.

If they can be primitive values, it's usually a mistake except your condition explicitly wants to test for the falsy values of the respective type. In your null-comparison case it would a mistake.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375