8
GC97
7y

Prefer if(typeof variable != "undefined") over if(variable)

Comments
  • 0
    Can you explain why?
  • 1
    @Shmanio it's more explicit, and also if (something) in JS will also resolve to false, if something is 0, false, an empty array, null, an empty string etc., even if it is defined
  • 0
    @heikomat @Shmanio Exactly - it's a story which I learned several Weeks ago where I really messed Up and Crashed all devices in production because the variable I refered to had to be strictly true (given)
    I Posted about it. You can read about it if you click on my profile
  • 2
    if(undefined!==variable)
    Or
    if(angular.isDefined(variable))
    Is what I use in most cases.
  • 0
    Or learn what truthiness is in js.
Add Comment