4
if(typeof hello! = 'undefined'){

}

This is too hard to type, would like to use underscore

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • 6
    Did you take two seconds to [search here](http://stackoverflow.com/search?q=%5Bjavascript%5D+underscore+check+for+undefined)? Yikes. – epascarello Mar 05 '13 at 03:32
  • 1
    `hello === undefined` should work well, even without underscore .. but in many cases I find - and design code such that - a simple "false-y" conditional is correct: `if (!hello) ..` The only reason to use `typeof` here is 1) for global variables, which may not exist (ick, prefer `window.prop` to avoid ReferenceErrors!) or 2) over paranoia about `undefined` being "redefined". –  Mar 05 '13 at 03:38

2 Answers2

26

According to the official documentation, you can use _.isUndefined():

_.isUndefined(window.missingVariable);
=> true
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
  • 1
    It seems this only works for object properties, but not for local vars: ```_.isUndefined(hello) => Uncaught ReferenceError: hello is not defined(…)``` (Tested in Chrome 52) – nickel715 Aug 11 '16 at 08:56
  • 3
    Local variables can be checked if they're first declared: `var a; _.isUndefined(a);` Attempting to access an undeclared variable will always throw a ReferenceError unless checked via `typeof a === "undefined"`. However, this question was about how to check for undefined via Underscore.js. – Platinum Azure Aug 11 '16 at 22:32
1

You mean this? http://underscorejs.org/#isUndefined

_.isUndefined(value)
chinabuffet
  • 5,278
  • 9
  • 40
  • 64