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

}

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

2
  • 6
    Did you take two seconds to search here? Yikes. Commented Mar 5, 2013 at 3: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". Commented Mar 5, 2013 at 3:38

2 Answers 2

26

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

_.isUndefined(window.missingVariable);
=> true
Sign up to request clarification or add additional context in comments.

2 Comments

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)
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.
1

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

_.isUndefined(value)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.