Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

9
  • 29
    the first code-piece can be incorrect if x is being set from a function call. like x = A(); if A doesnt return anything, it will return "undefined" by default. Doing a !x would be true which would be logically correct. However, if A() returns 0 then !x should be false as x=0. However in JS, !0 is also true. Commented Dec 30, 2009 at 0:49
  • the second code can be shortened to: if(!typeof(XX)){ ... }else{ ... } Commented Jun 6, 2014 at 21:53
  • 2
    @AlejandroSilva Sorry for late reply. That won't work since typeof returns a string, so it will return 'undefined' for an undefined variable, which in turn will evaluate as TRUE therefore leading to a false positive of a defined var. Commented Mar 17, 2015 at 20:29
  • 5
    Please get rid of the first snippet, it's just bad Commented Feb 12, 2016 at 12:06
  • 2
    Other comments have pointed out that the first example is bad, but not clearly why. So, for any new coders: !x doesn't test whether x is defined, but whether it's truthy. Strings, boolean true, and positive numbers are all truthy (and I might be forgetting some things), but other potentially valid values like 0, boolean false, and an empty string are not truthy. The first example can work for specific use cases (e.g., testing for a string if you can treat empty the same as undefined), but because of the many where it won't, it should not be considered the default way to check. Commented Nov 14, 2018 at 16:50