3201

How do I check if an object property in JavaScript is undefined?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Matt Sheppard
  • 116,545
  • 46
  • 111
  • 131
  • Look for recent answers in this thread. In 'modern' javascript, consider using the `in` operator:`'key' in obj ? 'obj has key property' : 'obj does not have key property'` ` – AlejandroVD Aug 23 '21 at 16:19
  • I’m open to picking a new ‘correct’ answer if you have one in mind that covers the old way as completely as the current one and also addresses more modern options. – Matt Sheppard Aug 24 '21 at 20:59

49 Answers49

2927

The usual way to check if the value of a property is the special value undefined, is:

if(o.myProperty === undefined) {
  alert("myProperty value is the special value `undefined`");
}

To check if an object does not actually have such a property, and will therefore return undefined by default when you try to access it:

if(!o.hasOwnProperty('myProperty')) {
  alert("myProperty does not exist");
}

To check if the value associated with an identifier is the special value undefined, or if that identifier has not been declared:

if(typeof myVariable === 'undefined') {
  alert('myVariable is either the special value `undefined`, or it has not been declared');
}

Note: this last method is the only way to refer to an undeclared identifier without an early error, which is different from having a value of undefined.

In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.

However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.

If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined value itself:

if(myVariable === void 0) {
  alert("myVariable is the special value `undefined`");
}
MWO
  • 2,627
  • 2
  • 10
  • 25
  • 10
    if something is null the it is defined (as null), but you can conjugate the too checks. The annoying detail of the above code is that you can't define a function to check it, well you can define the function... but try to use it. – neu-rah Jun 25 '12 at 19:20
  • 6
    @neu-rah why can't you write a function? why wouldn't something like this work? It seems to work for me. Is there a case I'm not considering? http://jsfiddle.net/djH9N/6/ – Zack Sep 24 '12 at 19:01
  • 8
    @Zack Your tests for isNullorUndefined did not consider the case where you call isNullOrUndefined(f) and f is undeclared (i.e. where there is no "var f" declaration). – pnkfelix Feb 15 '13 at 15:08
  • 144
    Blah, thousands of votes now. This is the worst possible way to do it. I hope passers-by see this comment and decide to check… ahem… *other* answers. – Ry- May 14 '14 at 03:05
  • 22
    You can just use `obj !== undefined` now. `undefined` used to be mutable, like `undefined = 1234` what would cause interesting results. But after Ecmascript 5, it's not writable anymore, so we can use the simpler version. http://www.codereadability.com/how-to-check-for-undefined-in-javascript/ – Bruno Buccolo Mar 15 '16 at 20:50
  • 1
    @Ryan what "other answer"? – user1032531 Dec 14 '17 at 12:41
  • 6
    @user1032531: I’d recommend mine – Ry- Dec 14 '17 at 20:02
  • grrr im just gonna `typeof window !== typeof undefined`... no chance of misspelling undefined and works on the global scope – Ray Foss Feb 04 '21 at 21:53
  • eslint advices against using `hasOwnProperty`. Use the `in` operator, see recent answers as examples. – AlejandroVD Aug 23 '21 at 16:22
982

I believe there are a number of incorrect answers to this topic. Contrary to common belief, "undefined" is not a keyword in JavaScript and can in fact have a value assigned to it.

Correct Code

The most robust way to perform this test is:

if (typeof myVar === "undefined")

This will always return the correct result, and even handles the situation where myVar is not declared.

Degenerate code. DO NOT USE.

var undefined = false;  // Shockingly, this is completely legal!
if (myVar === undefined) {
    alert("You have been misled. Run away!");
}

Additionally, myVar === undefined will raise an error in the situation where myVar is undeclared.

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
MarkPflug
  • 28,292
  • 8
  • 46
  • 54
  • 1
    I agree that undefined is not a keyword, undefined is a predefined variable with an undefined value. Something like alert, this is a function that you can override with something else. Alert is also not a keyword but a part of the standard function set, ap part of the window object that has a global scope. Like undefined you can also override the alert function by re-assigning it. For example: window.alert = function(s) { console.log(s); } is also a legal construction. – Codebeat Nov 08 '12 at 06:49
  • What about `if(typeof myVar != "undefined")`. Is the `"!="` acceptable? – Kevin Meredith Jul 05 '13 at 16:17
  • 25
    in addition to Marks comments, I don't get this: "myVar === undefined will raise an error in the situation where myVar is undeclared." - why is this bad? Why would I *not* want to have an error if I'm referencing undeclared variables? – eis Aug 20 '13 at 15:12
  • 2
    @Kevin Yes, it would be, because `typeof` will always return a string, making the type-safe comparison unnecessary. It's just considered a good practice to use `===` resp. `!==` exclusively. Actually I think that jQuery uses only `!=`. – Ingo Bürk Aug 23 '13 at 22:00
  • 6
    Also keep in mind you can always do `void 0` to get the value that `undefined` points to. So you can do `if (myVar === void 0)`. the `0` isn't special, you can literally put any expression there. – Claudiu Oct 03 '13 at 17:45
  • 35
    In modern browsers (FF4+, IE9+, Chrome unknown), it's no longer possible to modify `undefined`. [MDN: undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) – user247702 Feb 07 '14 at 14:09
  • [fiddle for demonstration](http://jsfiddle.net/rblakeley/rvk4kweg/) of this point – rojobuffalo Jan 16 '15 at 19:18
  • @Stijn: While it's not possible to modify the global `undefined`, it's still possible to *redefine* it locally as is shown in this answer. Copy and paste the answer's sample code into a modern browser and you'll see that `myVar === undefined` can still cause problems. – dharcourt Oct 02 '15 at 19:12
  • @KevinMeredith "Is the "!=" acceptable?" It certainly is. In my book it is *better* than `!==` as it's shorter and the longer forms offers no benefits i.c.w. `typeof`. – Stijn de Witt Nov 01 '15 at 12:53
  • 13
    This answer is incorrect as well. The question was about undefined object properties, not undefined variables. There is a significant difference. It is, for example, perfectly reasonable to do `if (obj.field === undefined)`. I think the risk of someone doing `var undefined = false;` is overrated. You will have to program unreasonably defensive if you want to protect against all such kinds of side effects caused by poor programming. – Zero3 Dec 15 '15 at 15:38
  • 2
    Rule X: NEVER use reserved words as variablename, functionname or whatever. Don't understand you get so many positive votes. Because it is possible it doesn't mean it's legal, besides, it can change in future and your code (and everything rely on it) doesn't work any longer. This is a bad/unreliable example and shows you how not do it. – Codebeat Nov 23 '16 at 05:16
  • since writable property of undefined is set to false. even if you assign false to undefined it will not get set. so undefined will be "undefined" always not false so your answer makes no sense. You can check that in ECMA script specification for JavaScript. https://www.ecma-international.org/ecma-262/5.1/#sec-15.1.1.3 – Velu S Gautam Jul 25 '17 at 12:36
  • 3
    Just from experience, I think you *really* want your code to throw that ReferenceError if a variable is not declared. It's so frustrating when things silently fail. – Atav32 Jul 31 '17 at 13:02
  • 4
    @MarkPflug: It didn’t make sense in 2010 either, sorry. `undefined` is not a keyword in 2017. You can still use `var undefined = false;`. The answer to this has always been “don’t do that” rather than “use convoluted workarounds for something that is never the case”. – Ry- Aug 16 '17 at 00:17
  • 10
    Funny that people suggest these silly and error-prone hacks to avoid a shadowed `undefined` (which could only be done by a terrible developer), yet they blithely use other global identifiers that could also have been shadowed. Bizarre. Just bizarre. –  Dec 18 '17 at 13:39
  • 1
    ^ totally agree. someone who might shadow `undefined` might also shadow `Math` or assign `Function.prototype.apply` or _anything_ else that you take for granted! Please. ^ totally agree. someone who might shadow `undefined` might also shadow `Math` or assign `Function.prototype.apply` or _anything_ else that you take for granted! Please. How about `Object.prototype.toJSON=()=>({rick:'rolled'})`? `JSON.stringify({hello:'world'}) === '{"rick":"rolled"}'` then. There are so many ways to break the expected JavaScript environment, you can't write code that works around all of those things. – CherryDT Mar 17 '20 at 21:13
  • But it is [no longer relevant with ECMAScript 5 (and later)](https://stackoverflow.com/questions/3390396/how-can-i-check-for-undefined-in-javascript/3390468#3390468)? – Peter Mortensen Jul 24 '20 at 23:38
  • do you need to check on window object if typeof myVar === "undefined" or is it obsolete if you use if(myvar) {} – strix25 Sep 01 '22 at 08:51
283

Many answers here are vehement in recommending typeof, but typeof is a bad choice. It should never be used for checking whether variables have the value undefined, because it acts as a combined check for the value undefined and for whether a variable exists. In the vast majority of cases, you know when a variable exists, and typeof will just introduce the potential for a silent failure if you make a typo in the variable name or in the string literal 'undefined'.

var snapshot = …;

if (typeof snaposhot === 'undefined') {
    //         ^
    // misspelled¹ – this will never run, but it won’t throw an error!
}
var foo = …;

if (typeof foo === 'undefned') {
    //                   ^
    // misspelled – this will never run, but it won’t throw an error!
}

So unless you’re doing feature detection², where there’s uncertainty whether a given name will be in scope (like checking typeof module !== 'undefined' as a step in code specific to a CommonJS environment), typeof is a harmful choice when used on a variable, and the correct option is to compare the value directly:

var foo = …;

if (foo === undefined) {
    ⋮
}

Some common misconceptions about this include:

  • that reading an “uninitialized” variable (var foo) or parameter (function bar(foo) { … }, called as bar()) will fail. This is simply not true – variables without explicit initialization and parameters that weren’t given values always become undefined, and are always in scope.

  • that undefined can be overwritten. It’s true that undefined isn’t a keyword, but it is read-only and non-configurable. There are other built-ins you probably don’t avoid despite their non-keyword status (Object, Math, NaN…) and practical code usually isn’t written in an actively malicious environment, so this isn’t a good reason to be worried about undefined. (But if you are writing a code generator, feel free to use void 0.)

With how variables work out of the way, it’s time to address the actual question: object properties. There is no reason to ever use typeof for object properties. The earlier exception regarding feature detection doesn’t apply here – typeof only has special behaviour on variables, and expressions that reference object properties are not variables.

This:

if (typeof foo.bar === 'undefined') {
    ⋮
}

is always exactly equivalent to this³:

if (foo.bar === undefined) {
    ⋮
}

and taking into account the advice above, to avoid confusing readers as to why you’re using typeof, because it makes the most sense to use === to check for equality, because it could be refactored to checking a variable’s value later, and because it just plain looks better, you should always use === undefined³ here as well.

Something else to consider when it comes to object properties is whether you really want to check for undefined at all. A given property name can be absent on an object (producing the value undefined when read), present on the object itself with the value undefined, present on the object’s prototype with the value undefined, or present on either of those with a non-undefined value. 'key' in obj will tell you whether a key is anywhere on an object’s prototype chain, and Object.prototype.hasOwnProperty.call(obj, 'key') will tell you whether it’s directly on the object. I won’t go into detail in this answer about prototypes and using objects as string-keyed maps, though, because it’s mostly intended to counter all the bad advice in other answers irrespective of the possible interpretations of the original question. Read up on object prototypes on MDN for more!

¹ unusual choice of example variable name? this is real dead code from the NoScript extension for Firefox.
² don’t assume that not knowing what’s in scope is okay in general, though. bonus vulnerability caused by abuse of dynamic scope: Project Zero 1225
³ once again assuming an ES5+ environment and that undefined refers to the undefined property of the global object.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 1
    Any non-default context can also overwrite, say, `Math`, or `Object`, or `setTimeout`, or literally anything that you expect to find in the global scope by default. – CherryDT Mar 17 '20 at 21:21
  • ohw kay foo !== void 0 works and is shorter guess i can use that :3 and i knew you were referring to yer own answer when ya commented that >:D – Fuseteam Jul 29 '20 at 23:54
  • now it doesn't document what it does tho and might be confusing to read so instead i'll make a function isDefined return true if is not void 0 and false if it is and return that instead >:3 – Fuseteam Jul 30 '20 at 00:02
  • @Fuseteam: Use `!== undefined`. Actually, I should probably remove the advice about `void 0`. – Ry- Jul 30 '20 at 00:18
  • @Fuseteam: It’s not as readable and has no practical advantages over `undefined`. – Ry- Jul 30 '20 at 18:41
  • i worked around the readability by wrapping it in a function isDefined(variable) so now i can just call that function to do it like `if(isDefined(variable))//do something` xD so it's both shorter and reusable i guess – Fuseteam Jul 30 '20 at 19:54
  • @Fuseteam: Again, I would strongly recommend not doing that, and writing `if (variable !== undefined)` instead. Comparisons with `undefined` are unambiguous and familiar, redundant wrapper functions create uncertainty (“maybe this also checks for `null`?”) with no readability benefit. – Ry- Jul 30 '20 at 20:00
  • i was actually looking into what other type of "undefined" values are possible but fair enough – Fuseteam Jul 30 '20 at 20:06
174

In JavaScript there is null and there is undefined. They have different meanings.

  • undefined means that the variable value has not been defined; it is not known what the value is.
  • null means that the variable value is defined and set to null (has no value).

Marijn Haverbeke states, in his free, online book "Eloquent JavaScript" (emphasis mine):

There is also a similar value, null, whose meaning is 'this value is defined, but it does not have a value'. The difference in meaning between undefined and null is mostly academic, and usually not very interesting. In practical programs, it is often necessary to check whether something 'has a value'. In these cases, the expression something == undefined may be used, because, even though they are not exactly the same value, null == undefined will produce true.

So, I guess the best way to check if something was undefined would be:

if (something == undefined)

Object properties should work the same way.

var person = {
    name: "John",
    age: 28,
    sex: "male"
};

alert(person.name); // "John"
alert(person.fakeVariable); // undefined
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pandincus
  • 9,506
  • 9
  • 43
  • 61
  • 46
    if (something == undefined) is better written as if (something === undefined) – Sebastian Rittau Nov 30 '09 at 09:47
  • 61
    It should be pointed out that this is not entirely safe. `undefined` is just a variable that can be re-assigned by the user: writing `undefined = 'a';` will cause your code to no longer do what you think it does. Using `typeof` is better and also works for variables (not just properties) that haven't been declared. – Gabe Moothart Apr 14 '10 at 15:18
  • 7
    if something is an undefined global variable, (something == undefined) brings up javascript error. – Morgan Cheng Apr 21 '10 at 03:04
  • 8
    The problem with this is that if var a = null then a == undefined evaluates to true, even though a is most certainly defined. – Andrew May 19 '11 at 18:50
  • 1
    `if (something === undefined)` is not working for me with ie7 or ie8 `if (typeof something == "undefined")` is. – juhan_h Jun 14 '11 at 07:21
  • 7
    This interpretation of the "Eloquent Javascript" comment is _backward_. If you really do just want to check for undefined, the suggested code will not work (it will also detect the condition defined but no value has been assined yet [i.e.null]).a null value. The suggested code "if (something == undefined) ..." checks for _both_ undefined and null (no value set), i.e. it's interpreted as "if ((something is undefined) OR (something is null)) ..." What the author is saying is that often what you _really_ want is to check for _both_ undefined and null. – Chuck Kollars May 17 '12 at 22:35
137

What does this mean: "undefined object property"?

Actually it can mean two quite different things! First, it can mean the property that has never been defined in the object and, second, it can mean the property that has an undefined value. Let's look at this code:

var o = { a: undefined }

Is o.a undefined? Yes! Its value is undefined. Is o.b undefined? Sure! There is no property 'b' at all! OK, see now how different approaches behave in both situations:

typeof o.a == 'undefined' // true
typeof o.b == 'undefined' // true
o.a === undefined // true
o.b === undefined // true
'a' in o // true
'b' in o // false

We can clearly see that typeof obj.prop == 'undefined' and obj.prop === undefined are equivalent, and they do not distinguish those different situations. And 'prop' in obj can detect the situation when a property hasn't been defined at all and doesn't pay attention to the property value which may be undefined.

So what to do?

1) You want to know if a property is undefined by either the first or second meaning (the most typical situation).

obj.prop === undefined // IMHO, see "final fight" below

2) You want to just know if object has some property and don't care about its value.

'prop' in obj

Notes:

  • You can't check an object and its property at the same time. For example, this x.a === undefined or this typeof x.a == 'undefined' raises ReferenceError: x is not defined if x is not defined.
  • Variable undefined is a global variable (so actually it is window.undefined in browsers). It has been supported since ECMAScript 1st Edition and since ECMAScript 5 it is read only. So in modern browsers it can't be redefined to true as many authors love to frighten us with, but this is still a true for older browsers.

Final fight: obj.prop === undefined vs typeof obj.prop == 'undefined'

Pluses of obj.prop === undefined:

  • It's a bit shorter and looks a bit prettier
  • The JavaScript engine will give you an error if you have misspelled undefined

Minuses of obj.prop === undefined:

  • undefined can be overridden in old browsers

Pluses of typeof obj.prop == 'undefined':

  • It is really universal! It works in new and old browsers.

Minuses of typeof obj.prop == 'undefined':

  • 'undefned' (misspelled) here is just a string constant, so the JavaScript engine can't help you if you have misspelled it like I just did.

Update (for server-side JavaScript):

Node.js supports the global variable undefined as global.undefined (it can also be used without the 'global' prefix). I don't know about other implementations of server-side JavaScript.

Konstantin Smolyanin
  • 17,579
  • 12
  • 56
  • 56
  • @Bergi thank you for your comment. I have corrected my answer. In my defense I can say that currently (as of v.0.10.18) [official Node.js documentation](http://nodejs.org/api/globals.html) says nothing about `undefined` as a member of `global`. Also neither `console.log(global);` nor `for (var key in global) { ... }` doesn't show *undefined* as a member of *global*. But test like `'undefined' in global` show the opposite. – Konstantin Smolyanin Sep 11 '13 at 10:53
  • 4
    It didn't need extra documentation since [it's in the EcmaScript spec](http://es5.github.io/#x15.1.1.3), which also says that `[[Enumerable]]` is false :-) – Bergi Sep 11 '13 at 11:00
  • 5
    Regarding `Minuses of typeof obj.prop == 'undefined'`, this can be avoided by writing as `typeof obj.prop == typeof undefined`. This also gives a very nice symmetry. – hlovdal Oct 24 '14 at 11:01
  • 3
    @hlovdal: That’s totally pointless vs. `obj.prop === undefined`. – Ry- Apr 11 '18 at 21:38
  • 2
    When we are true to the question headline **„_Detecting_ an undefined property“**, not true to the (different and much easier) question in the first sentence („check if undefined...“), you answer `if ('foo' in o`)… your answer is truly the first correct answer here. Pretty much everybody else just answers that sentence. – Frank N Jun 11 '18 at 08:46
75

The issue boils down to three cases:

  1. The object has the property and its value is not undefined.
  2. The object has the property and its value is undefined.
  3. The object does not have the property.

This tells us something I consider important:

There is a difference between an undefined member and a defined member with an undefined value.

But unhappily typeof obj.foo does not tell us which of the three cases we have. However we can combine this with "foo" in obj to distinguish the cases.

                               |  typeof obj.x === 'undefined' | !("x" in obj)
1.                     { x:1 } |  false                        | false
2.    { x : (function(){})() } |  true                         | false
3.                          {} |  true                         | true

Its worth noting that these tests are the same for null entries too

                               |  typeof obj.x === 'undefined' | !("x" in obj)
                    { x:null } |  false                        | false

I'd argue that in some cases it makes more sense (and is clearer) to check whether the property is there, than checking whether it is undefined, and the only case where this check will be different is case 2, the rare case of an actual entry in the object with an undefined value.

For example: I've just been refactoring a bunch of code that had a bunch of checks whether an object had a given property.

if( typeof blob.x != 'undefined' ) {  fn(blob.x); }

Which was clearer when written without a check for undefined.

if( "x" in blob ) { fn(blob.x); }

But as has been mentioned these are not exactly the same (but are more than good enough for my needs).

Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
  • 10
    Hi Michael. Great suggestion, and I think it does make things cleaner. One gotcha that I found, however, is when using the ! operator with "in". You have to say `if (!("x" in blob)) {}` with brackets around the in, because the ! operator has precedence over 'in'. Hope that helps someone. – Simon East Jun 15 '11 at 00:28
  • Sorry Michael, but this is incorrect, or at least misleading, in light of the original question. 'in' is not a sufficient way to test whether an object property has typeof undefined. For proof, please see this fiddle: http://jsfiddle.net/CsLKJ/4/ – tex Feb 25 '12 at 12:04
  • 2
    Those two code parts do a different thing! Consider and object given by `a = {b: undefined}`; then `typeof a.b === typeof a.c === 'undefined'` but `'b' in a` and `!('c' in a)`. – mgol Sep 27 '12 at 14:07
  • 3
    +1. The OP doesn't make it clear whether the property exists and has the value *undefined*, or whether the property itself is undefined (i.e. doesn't exist). – RobG Apr 01 '14 at 01:12
  • I would suggest changing point (2.) in your first table to `{ x : undefined }` or at least add it as another alternative to (2.) in the table - I had to think for a moment to realize that point (2.) evaluates to `undefined` (although you mention that later on). – mucaho May 14 '15 at 16:32
  • @mucaho That would be better, but I think there is (or at least used to be?) some issues with a construct like that - that is `undefined` is not (was not?) guaranteed to be undefined. – Michael Anderson May 15 '15 at 08:20
48
if ( typeof( something ) == "undefined") 

This worked for me while the others didn't.

Peter Ajtai
  • 56,972
  • 13
  • 121
  • 140
Kevin
  • 489
  • 4
  • 2
  • 50
    parens are unnecessary since typeof is an operator – aehlke Aug 10 '10 at 11:22
  • 13
    But they make it clearer what is being checked. Otherwise it might be read as `typeof (something == "undefined")`. – Abhi Beckert Sep 06 '12 at 00:28
  • If you need the parentheses, then you should learn operator precedence in JS: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence – Ian Mar 07 '14 at 17:17
  • 12
    Parenthesis are useful precisely because you do NOT need to learn operator precedence in JS, nor do you need to speculate whether future maintenance programmers will need to learn operator precedence in JS. – DaveWalley Apr 11 '14 at 14:48
  • 31
    Parenthesis are useful to clarify things. But in this case they just make the operator look like a function. No doubt this clarifies the intent of the programmer. But if you're unsure about operator precedence you should rather write it as `(typeof something) === "undefined"`. – Robert May 14 '14 at 18:31
  • @Robert I agree with your use of parens (surrounding `typeof`), but in ES6 you may not use parens to call a function, e.g. [`quux \`foo\n${ 42 }bar\``](http://es6-features.org/#RawStringAccess). – CPHPython Mar 07 '18 at 12:00
44

I'm not sure where the origin of using === with typeof came from, and as a convention I see it used in many libraries, but the typeof operator returns a string literal, and we know that up front, so why would you also want to type check it too?

typeof x;                      // some string literal "string", "object", "undefined"
if (typeof x === "string") {   // === is redundant because we already know typeof returns a string literal
if (typeof x == "string") {    // sufficient
Simon East
  • 55,742
  • 17
  • 139
  • 133
Eric
  • 473
  • 4
  • 2
  • Great point Eric. Is there a performance hit from checking type also? – Simon East Jun 29 '11 at 07:16
  • 6
    @Simon: quite the contrary - one could expect slight performance hit from avoiding coercion in '===' case. Quick and dirty test has shown '===' is 5% faster than '==' under FF5.0.1 – Antony Hatchkins Dec 18 '11 at 08:24
  • 6
    More thorough test has shown that under FF,IE and Chrome '==' is more or less faster than '===' (5-10%) and Opera doesn't make any difference at all: http://jsperf.com/triple-equals-vs-twice-equals/6 – Antony Hatchkins Dec 18 '11 at 09:55
  • 4
    Using `==` still requires _at least_ a type check - the interpreter can't compare the two operands without knowing their type first. – Alnitak Aug 13 '12 at 15:12
  • 8
    `==` is one less character than `===` :) – svidgen Jun 28 '13 at 14:54
  • @svidgen You add a smiley, but seeing that the network is the *slowest* chain in the link, I actually believe that you'll see more of a performance gain from leaving out the extra character then you'll ever see from the type checks. 5% of nothing is still nothing. Personally I hate dogmatic coding. I allows you to turn off your brain while typing, but there is *no* reason triple equals would be any safer in this case. – Stijn de Witt Nov 01 '15 at 02:21
31

I didn't see (hope I didn't miss it) anyone checking the object before the property. So, this is the shortest and most effective (though not necessarily the most clear):

if (obj && obj.prop) {
  // Do something;
}

If the obj or obj.prop is undefined, null, or "falsy", the if statement will not execute the code block. This is usually the desired behavior in most code block statements (in JavaScript).

UPDATE: (7/2/2021)

The latest version of JavaScript introduces a new operator for optional chaining: ?.

This is probably going to be the most explicit and efficient method of checking for the existence of object properties, moving forward.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Joe Johnson
  • 1,814
  • 16
  • 20
  • 2
    If you want to know why this works: [Javascript: Logical Operators and truthy / falsy](http://nfriedly.com/techblog/2009/07/advanced-javascript-operators-and-truthy-falsy/) – mb21 Feb 04 '13 at 16:57
  • if you want to assign the property to a variable if it's defined, not null and not falsey, else use some default value, you can use: `var x = obj && obj.prop || 'default';` – Stijn de Witt Nov 01 '15 at 02:27
  • I believe the question is for checking against undefined explicitly. Your condition check against all false values of JS. – NikoKyriakid Jul 20 '18 at 09:49
  • Don't do this, it fails if `obj.prop` is `false`, `0`, `""` and various other falsey values. This is exactly what we should not do and also applies to optional chaining, which should not be used in this manner. – Seth Apr 29 '22 at 00:11
27

Crossposting my answer from related question How can I check for "undefined" in JavaScript?.

Specific to this question, see test cases with someObject.<whatever>.


Some scenarios illustrating the results of the various answers: http://jsfiddle.net/drzaus/UVjM4/

(Note that the use of var for in tests make a difference when in a scoped wrapper)

Code for reference:

(function(undefined) {
    var definedButNotInitialized;
    definedAndInitialized = 3;
    someObject = {
        firstProp: "1"
        , secondProp: false
        // , undefinedProp not defined
    }
    // var notDefined;

    var tests = [
        'definedButNotInitialized in window',
        'definedAndInitialized in window',
        'someObject.firstProp in window',
        'someObject.secondProp in window',
        'someObject.undefinedProp in window',
        'notDefined in window',

        '"definedButNotInitialized" in window',
        '"definedAndInitialized" in window',
        '"someObject.firstProp" in window',
        '"someObject.secondProp" in window',
        '"someObject.undefinedProp" in window',
        '"notDefined" in window',

        'typeof definedButNotInitialized == "undefined"',
        'typeof definedButNotInitialized === typeof undefined',
        'definedButNotInitialized === undefined',
        '! definedButNotInitialized',
        '!! definedButNotInitialized',

        'typeof definedAndInitialized == "undefined"',
        'typeof definedAndInitialized === typeof undefined',
        'definedAndInitialized === undefined',
        '! definedAndInitialized',
        '!! definedAndInitialized',

        'typeof someObject.firstProp == "undefined"',
        'typeof someObject.firstProp === typeof undefined',
        'someObject.firstProp === undefined',
        '! someObject.firstProp',
        '!! someObject.firstProp',

        'typeof someObject.secondProp == "undefined"',
        'typeof someObject.secondProp === typeof undefined',
        'someObject.secondProp === undefined',
        '! someObject.secondProp',
        '!! someObject.secondProp',

        'typeof someObject.undefinedProp == "undefined"',
        'typeof someObject.undefinedProp === typeof undefined',
        'someObject.undefinedProp === undefined',
        '! someObject.undefinedProp',
        '!! someObject.undefinedProp',

        'typeof notDefined == "undefined"',
        'typeof notDefined === typeof undefined',
        'notDefined === undefined',
        '! notDefined',
        '!! notDefined'
    ];

    var output = document.getElementById('results');
    var result = '';
    for(var t in tests) {
        if( !tests.hasOwnProperty(t) ) continue; // bleh

        try {
            result = eval(tests[t]);
        } catch(ex) {
            result = 'Exception--' + ex;
        }
        console.log(tests[t], result);
        output.innerHTML += "\n" + tests[t] + ": " + result;
    }
})();

And results:

definedButNotInitialized in window: true
definedAndInitialized in window: false
someObject.firstProp in window: false
someObject.secondProp in window: false
someObject.undefinedProp in window: true
notDefined in window: Exception--ReferenceError: notDefined is not defined
"definedButNotInitialized" in window: false
"definedAndInitialized" in window: true
"someObject.firstProp" in window: false
"someObject.secondProp" in window: false
"someObject.undefinedProp" in window: false
"notDefined" in window: false
typeof definedButNotInitialized == "undefined": true
typeof definedButNotInitialized === typeof undefined: true
definedButNotInitialized === undefined: true
! definedButNotInitialized: true
!! definedButNotInitialized: false
typeof definedAndInitialized == "undefined": false
typeof definedAndInitialized === typeof undefined: false
definedAndInitialized === undefined: false
! definedAndInitialized: false
!! definedAndInitialized: true
typeof someObject.firstProp == "undefined": false
typeof someObject.firstProp === typeof undefined: false
someObject.firstProp === undefined: false
! someObject.firstProp: false
!! someObject.firstProp: true
typeof someObject.secondProp == "undefined": false
typeof someObject.secondProp === typeof undefined: false
someObject.secondProp === undefined: false
! someObject.secondProp: true
!! someObject.secondProp: false
typeof someObject.undefinedProp == "undefined": true
typeof someObject.undefinedProp === typeof undefined: true
someObject.undefinedProp === undefined: true
! someObject.undefinedProp: true
!! someObject.undefinedProp: false
typeof notDefined == "undefined": true
typeof notDefined === typeof undefined: true
notDefined === undefined: Exception--ReferenceError: notDefined is not defined
! notDefined: Exception--ReferenceError: notDefined is not defined
!! notDefined: Exception--ReferenceError: notDefined is not defined
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
drzaus
  • 24,171
  • 16
  • 142
  • 201
21

If you do

if (myvar == undefined )
{ 
    alert('var does not exists or is not initialized');
}

it will fail when the variable myvar does not exists, because myvar is not defined, so the script is broken and the test has no effect.

Because the window object has a global scope (default object) outside a function, a declaration will be 'attached' to the window object.

For example:

var myvar = 'test';

The global variable myvar is the same as window.myvar or window['myvar']

To avoid errors to test when a global variable exists, you better use:

if(window.myvar == undefined )
{ 
    alert('var does not exists or is not initialized');
}

The question if a variable really exists doesn't matter, its value is incorrect. Otherwise, it is silly to initialize variables with undefined, and it is better use the value false to initialize. When you know that all variables that you declare are initialized with false, you can simply check its type or rely on !window.myvar to check if it has a proper/valid value. So even when the variable is not defined then !window.myvar is the same for myvar = undefined or myvar = false or myvar = 0.

When you expect a specific type, test the type of the variable. To speed up testing a condition you better do:

if( !window.myvar || typeof window.myvar != 'string' )
{
    alert('var does not exists or is not type of string');
}

When the first and simple condition is true, the interpreter skips the next tests.

It is always better to use the instance/object of the variable to check if it got a valid value. It is more stable and is a better way of programming.

(y)

Codebeat
  • 6,501
  • 6
  • 57
  • 99
16

ECMAScript 10 introduced a new feature - optional chaining which you can use to use a property of an object only when an object is defined like this:

const userPhone = user?.contactDetails?.phone;

It will reference to the phone property only when user and contactDetails are defined.

Ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Przemek Struciński
  • 4,990
  • 1
  • 28
  • 20
15

In the article Exploring the Abyss of Null and Undefined in JavaScript I read that frameworks like Underscore.js use this function:

function isUndefined(obj){
    return obj === void 0;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marthijn
  • 3,292
  • 2
  • 31
  • 48
  • 3
    `void 0` is just a short way of writing `undefined` (since that's what *void* followed by any expression returns), it saves 3 charcters. It could also do `var a; return obj === a;`, but that's one more character. :-) – RobG Apr 01 '14 at 01:16
  • 2
    `void` is a reserved word, whereas `undefined` is not i.e. while `undefined` is equal to `void 0` by default, you can assign a value to `undefined` e.g. `undefined = 1234`. – Brian M. Hunt Sep 14 '15 at 13:08
  • `isUndefined(obj)`: 16 chars. `obj === void 0`: 14 chars. 'nough said. – Stijn de Witt Nov 01 '15 at 02:41
15

Simply anything is not defined in JavaScript, is undefined, doesn't matter if it's a property inside an Object/Array or as just a simple variable...

JavaScript has typeof which make it very easy to detect an undefined variable.

Simply check if typeof whatever === 'undefined' and it will return a boolean.

That's how the famous function isUndefined() in AngularJs v.1x is written:

function isUndefined(value) {return typeof value === 'undefined';} 

So as you see the function receive a value, if that value is defined, it will return false, otherwise for undefined values, return true.

So let's have a look what gonna be the results when we passing values, including object properties like below, this is the list of variables we have:

var stackoverflow = {};
stackoverflow.javascipt = 'javascript';
var today;
var self = this;
var num = 8;
var list = [1, 2, 3, 4, 5];
var y = null;

and we check them as below, you can see the results in front of them as a comment:

isUndefined(stackoverflow); //false
isUndefined(stackoverflow.javascipt); //false
isUndefined(today); //true
isUndefined(self); //false
isUndefined(num); //false
isUndefined(list); //false
isUndefined(y); //false
isUndefined(stackoverflow.java); //true
isUndefined(stackoverflow.php); //true
isUndefined(stackoverflow && stackoverflow.css); //true

As you see we can check anything with using something like this in our code, as mentioned you can simply use typeof in your code, but if you are using it over and over, create a function like the angular sample which I share and keep reusing as following DRY code pattern.

Also one more thing, for checking property on an object in a real application which you not sure even the object exists or not, check if the object exists first.

If you check a property on an object and the object doesn't exist, will throw an error and stop the whole application running.

isUndefined(x.css);
VM808:2 Uncaught ReferenceError: x is not defined(…)

So simple you can wrap inside an if statement like below:

if(typeof x !== 'undefined') {
  //do something
}

Which also equal to isDefined in Angular 1.x...

function isDefined(value) {return typeof value !== 'undefined';}

Also other javascript frameworks like underscore has similar defining check, but I recommend you use typeof if you already not using any frameworks.

I also add this section from MDN which has got useful information about typeof, undefined and void(0).

Strict equality and undefined
You can use undefined and the strict equality and inequality operators to determine whether a variable has a value. In the following code, the variable x is not defined, and the if statement evaluates to true.

var x;
if (x === undefined) {
   // these statements execute
}
else {
   // these statements do not execute
}

Note: The strict equality operator rather than the standard equality operator must be used here, because x == undefined also checks whether x is null, while strict equality doesn't. null is not equivalent to undefined. See comparison operators for details.


Typeof operator and undefined
Alternatively, typeof can be used:

var x;
if (typeof x === 'undefined') {
   // these statements execute
}

One reason to use typeof is that it does not throw an error if the variable has not been declared.

// x has not been declared before
if (typeof x === 'undefined') { // evaluates to true without errors
   // these statements execute
}

if (x === undefined) { // throws a ReferenceError

}

However, this kind of technique should be avoided. JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context. The only exception is the global scope, but the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object (using the in operator, for instance).


Void operator and undefined

The void operator is a third alternative.

var x;
if (x === void 0) {
   // these statements execute
}

// y has not been declared before
if (y === void 0) {
   // throws a ReferenceError (in contrast to `typeof`)
}

more > here

Alireza
  • 100,211
  • 27
  • 269
  • 172
13

'if (window.x) { }' is error safe

Most likely you want if (window.x). This check is safe even if x hasn't been declared (var x;) - browser doesn't throw an error.

Example: I want to know if my browser supports History API

if (window.history) {
    history.call_some_function();
}

How this works:

window is an object which holds all global variables as its members, and it is legal to try to access a non-existing member. If x hasn't been declared or hasn't been set then window.x returns undefined. undefined leads to false when if() evaluates it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DenisS
  • 1,637
  • 19
  • 15
13

Reading through this, I'm amazed I didn't see this. I have found multiple algorithms that would work for this.

Never Defined

If the value of an object was never defined, this will prevent from returning true if it is defined as null or undefined. This is helpful if you want true to be returned for values set as undefined

if(obj.prop === void 0) console.log("The value has never been defined");

Defined as undefined Or never Defined

If you want it to result as true for values defined with the value of undefined, or never defined, you can simply use === undefined

if(obj.prop === undefined) console.log("The value is defined as undefined, or never defined");

Defined as a falsy value, undefined,null, or never defined.

Commonly, people have asked me for an algorithm to figure out if a value is either falsy, undefined, or null. The following works.

if(obj.prop == false || obj.prop === null || obj.prop === undefined) {
    console.log("The value is falsy, null, or undefined");
}
Travis
  • 1,274
  • 1
  • 16
  • 33
  • 4
    I think you can replace the last example with `if (!obj.prop)` – Stijn de Witt Nov 01 '15 at 02:24
  • @StijndeWitt, you can, I was pretty inexperienced when I wrote this, and my English seems to have been equally bad, nevertheless, there isn't anything *incorrect* in the answer – Travis Apr 07 '17 at 14:31
  • 3
    `var obj = {foo: undefined}; obj.foo === void 0` -> `true`. How is that "never defined as `undefined`"? This is wrong. – Patrick Roberts Jun 15 '17 at 18:40
  • @PatrickRoberts You're right. When I wrote this answer in February 2015 (before ES6) the first option I outlined did indeed work, but it is now outdated. – Travis May 14 '20 at 22:31
12
"propertyName" in obj //-> true | false
sam
  • 40,318
  • 2
  • 41
  • 37
12

The solution is incorrect. In JavaScript,

null == undefined

will return true, because they both are "casted" to a boolean and are false. The correct way would be to check

if (something === undefined)

which is the identity operator...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ricky
  • 5,365
  • 2
  • 32
  • 30
  • 3
    To be clear, `===` is type equality + (primitive equality | object identity), where primitives include strings. I think most people consider `'abab'.slice(0,2) === 'abab'.slice(2)` unintuitive if one considers `===` as the identity operator. – clacke Jul 30 '10 at 08:49
  • 1
    Wrong. This throws an error if the variable has not been created. Should not be voted up. Use typeof instead. – Simon East Jun 15 '11 at 00:22
  • What solution? Can you link directly to it? – Peter Mortensen Jul 24 '20 at 23:34
10

Compare with void 0, for terseness.

if (foo !== void 0)

It's not as verbose as if (typeof foo !== 'undefined')

bevacqua
  • 47,502
  • 56
  • 171
  • 285
  • 3
    But it will throw a ReferenceError if `foo` is undeclared. – daniel1426 Mar 07 '14 at 22:46
  • 1
    @daniel1426: So if there's an error in your code, you want to hide it instead of fixing it? Not a great approach, IMO. –  Dec 18 '17 at 13:47
  • This is not used to hide errors. It's the common way to detect the properties of the environment to define polyfills. For instance: if( typeof Promise === 'undefined' ){ /* define Promise */ } – gaperton Oct 04 '18 at 03:05
10

You can get an array all undefined with path using the following code.

 function getAllUndefined(object) {

        function convertPath(arr, key) {
            var path = "";
            for (var i = 1; i < arr.length; i++) {

                path += arr[i] + "->";
            }
            path += key;
            return path;
        }


        var stack = [];
        var saveUndefined= [];
        function getUndefiend(obj, key) {

            var t = typeof obj;
            switch (t) {
                case "object":
                    if (t === null) {
                        return false;
                    }
                    break;
                case "string":
                case "number":
                case "boolean":
                case "null":
                    return false;
                default:
                    return true;
            }
            stack.push(key);
            for (k in obj) {
                if (obj.hasOwnProperty(k)) {
                    v = getUndefiend(obj[k], k);
                    if (v) {
                        saveUndefined.push(convertPath(stack, k));
                    }
                }
            }
            stack.pop();

        }

        getUndefiend({
            "": object
        }, "");
        return saveUndefined;
    }

jsFiddle link

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anoop
  • 23,044
  • 10
  • 62
  • 76
  • While it won't affect the validity of your code, you've got a typo: `getUndefiend` should be `getUndefined`. – icktoofay May 14 '13 at 03:02
9

There is a nice and elegant way to assign a defined property to a new variable if it is defined or assign a default value to it as a fallback if it’s undefined.

var a = obj.prop || defaultValue;

It’s suitable if you have a function, which receives an additional configuration property:

var yourFunction = function(config){

   this.config = config || {};
   this.yourConfigValue = config.yourConfigValue || 1;
   console.log(this.yourConfigValue);
}

Now executing

yourFunction({yourConfigValue:2});
//=> 2

yourFunction();
//=> 1

yourFunction({otherProperty:5});
//=> 1
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marian Klühspies
  • 15,824
  • 16
  • 93
  • 136
  • Using || (OR) will use type coertion for "undefined" and "null" values to false, and every other values to "true". ------- If property checked (in example "obj.prop" and "config") is undefined or null it will be assigned 'default value'. In any other the value will not be changed. -------- This soultion doesn't check if the object HAS property defined. ------------------------------------------------ To check if object has a property you can use: `let objAndPropCheck = (obj || { }).prop || 0;` – konieckropka Mar 04 '22 at 00:44
8

Here is my situation:

I am using the result of a REST call. The result should be parsed from JSON to a JavaScript object.

There is one error I need to defend. If the arguments to the REST call were incorrect as far as the user specifying the arguments wrong, the REST call comes back basically empty.

While using this post to help me defend against this, I tried this:

if( typeof restResult.data[0] === "undefined" ) { throw  "Some error"; }

For my situation, if restResult.data[0] === "object", then I can safely start inspecting the rest of the members. If undefined then throw the error as above.

What I am saying is that for my situation, all the previous suggestions in this post did not work. I'm not saying I'm right and everyone is wrong. I am not a JavaScript master at all, but hopefully this will help someone.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
wayneseymour
  • 391
  • 4
  • 5
  • Your `typeof` guard doesn't actually guard against anything that a direct comparison couldn't handle. If `restResult` is undefined or undeclared, it'll still throw. –  Dec 18 '17 at 13:50
  • In your case you could more simply check if the array is empty: `if(!restResult.data.length) { throw "Some error"; }` – Headbank Feb 28 '19 at 15:36
7

All the answers are incomplete. This is the right way of knowing that there is a property 'defined as undefined':

var hasUndefinedProperty = function hasUndefinedProperty(obj, prop){
  return ((prop in obj) && (typeof obj[prop] == 'undefined'));
};

Example:

var a = { b : 1, e : null };
a.c = a.d;

hasUndefinedProperty(a, 'b'); // false: b is defined as 1
hasUndefinedProperty(a, 'c'); // true: c is defined as undefined
hasUndefinedProperty(a, 'd'); // false: d is undefined
hasUndefinedProperty(a, 'e'); // false: e is defined as null

// And now...
delete a.c ;
hasUndefinedProperty(a, 'c'); // false: c is undefined

Too bad that this been the right answer and is buried in wrong answers >_<

So, for anyone who pass by, I will give you undefined's for free!!

var undefined ; undefined ; // undefined
({}).a ;                    // undefined
[].a ;                      // undefined
''.a ;                      // undefined
(function(){}()) ;          // undefined
void(0) ;                   // undefined
eval() ;                    // undefined
1..a ;                      // undefined
/a/.a ;                     // undefined
(true).a ;                  // undefined
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Juan Garcia
  • 714
  • 6
  • 23
7

There is a very easy and simple way.

You can use optional chaining:

x = {prop:{name:"sajad"}}

console.log(x.prop?.name) // Output is: "sajad"
console.log(x.prop?.lastName) // Output is: undefined

or

if(x.prop?.lastName) // The result of this 'if' statement is false and is not throwing an error

You can use optional chaining even for functions or arrays.

As of mid-2020 this is not universally implemented. Check the documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

user1527225
  • 1,059
  • 9
  • 7
S.Saderi
  • 4,755
  • 3
  • 21
  • 23
6

Going through the comments, for those who want to check both is it undefined or its value is null:

//Just in JavaScript
var s; // Undefined
if (typeof s == "undefined" || s === null){
    alert('either it is undefined or value is null')
}

If you are using jQuery Library then jQuery.isEmptyObject() will suffice for both cases,

var s; // Undefined
jQuery.isEmptyObject(s); // Will return true;

s = null; // Defined as null
jQuery.isEmptyObject(s); // Will return true;

//Usage
if (jQuery.isEmptyObject(s)) {
    alert('Either variable:s is undefined or its value is null');
} else {
     alert('variable:s has value ' + s);
}

s = 'something'; // Defined with some value
jQuery.isEmptyObject(s); // Will return false;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Angelin Nadar
  • 8,944
  • 10
  • 43
  • 53
6

If you are using Angular:

angular.isUndefined(obj)
angular.isUndefined(obj.prop)

Underscore.js:

_.isUndefined(obj) 
_.isUndefined(obj.prop) 
Vitalii Fedorenko
  • 110,878
  • 29
  • 149
  • 111
  • 2
    How do I add `1` to variable `x`? Do I need Underscore or jQuery? (amazing that people will use libraries for even the most elementary operations such as a `typeof` check) – Stijn de Witt Nov 01 '15 at 02:43
6

I provide three ways here for those who expect weird answers:

function isUndefined1(val) {
    try {
        val.a;
    } catch (e) {
        return /undefined/.test(e.message);
    }
    return false;
}

function isUndefined2(val) {
    return !val && val+'' === 'undefined';
}

function isUndefined3(val) {
    const defaultVal = {};
    return ((input = defaultVal) => input === defaultVal)(val);
}

function test(func){
    console.group(`test start :`+func.name);
    console.log(func(undefined));
    console.log(func(null));
    console.log(func(1));
    console.log(func("1"));
    console.log(func(0));
    console.log(func({}));
    console.log(func(function () { }));
    console.groupEnd();
}
test(isUndefined1);
test(isUndefined2);
test(isUndefined3);

isUndefined1:

Try to get a property of the input value, and check the error message if it exists. If the input value is undefined, the error message would be Uncaught TypeError: Cannot read property 'b' of undefined.

isUndefined2:

Convert the input value to a string to compare with "undefined" and ensure it's a negative value.

isUndefined3:

In JavaScript, an optional parameter works when the input value is exactly undefined.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
blackmiaool
  • 5,234
  • 2
  • 22
  • 39
5

I use if (this.variable) to test if it is defined. A simple if (variable), recommended in a previous answer, fails for me.

It turns out that it works only when a variable is a field of some object, obj.someField to check if it is defined in the dictionary. But we can use this or window as the dictionary object since any variable is a field in the current window, as I understand it. Therefore here is a test:

if (this.abc) 
    alert("defined"); 
else 
    alert("undefined");

abc = "abc";
if (this.abc) 
    alert("defined"); 
else 
    alert("undefined");

It first detects that variable abc is undefined and it is defined after initialization.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Val
  • 1
  • 8
  • 40
  • 64
4

I would like to show you something I'm using in order to protect the undefined variable:

Object.defineProperty(window, 'undefined', {});

This forbids anyone to change the window.undefined value therefore destroying the code based on that variable. If using "use strict", anything trying to change its value will end in error, otherwise it would be silently ignored.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Seti
  • 2,169
  • 16
  • 26
4
function isUnset(inp) {
  return (typeof inp === 'undefined')
}

Returns false if variable is set, and true if is undefined.

Then use:

if (isUnset(var)) {
  // initialize variable here
}
Simon East
  • 55,742
  • 17
  • 139
  • 133
Rixius
  • 2,223
  • 3
  • 24
  • 33
  • 5
    No. Don't do this. It only takes a [very simple test](https://jsfiddle.net/wcj6xpa7/1/) to prove that you cannot meaningfully wrap a `typeof` test in a function. Amazing that 4 people upvoted this. -1. – Stijn de Witt Nov 01 '15 at 02:39
4

From lodash.js.

var undefined;
function isUndefined(value) {
  return value === undefined;
}

It creates a local variable named undefined which is initialized with the default value -- the real undefined, then compares value with the variable undefined.


Update 9/9/2019

I found Lodash updated its implementation. See my issue and the code.

To be bullet-proof, simply use:

function isUndefined(value) {
  return value === void 0;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
lzl124631x
  • 4,485
  • 2
  • 30
  • 49
4

You can also use a Proxy. It will work with nested calls, but it will require one extra check:

function resolveUnknownProps(obj, resolveKey) {
  const handler = {
    get(target, key) {
      if (
        target[key] !== null &&
        typeof target[key] === 'object'
      ) {
        return resolveUnknownProps(target[key], resolveKey);
      } else if (!target[key]) {
        return resolveUnknownProps({ [resolveKey]: true }, resolveKey);
      }

      return target[key];
    },
  };

  return new Proxy(obj, handler);
}

const user = {}

console.log(resolveUnknownProps(user, 'isUndefined').personalInfo.name.something.else); // { isUndefined: true }

So you will use it like:

const { isUndefined } = resolveUnknownProps(user, 'isUndefined').personalInfo.name.something.else;
if (!isUndefined) {
  // Do something
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sarkis Arutiunian
  • 1,281
  • 3
  • 17
  • 34
4

In recent JavaScript release there is new chaining operator introduced, which is most probably best way to check if property exists else it will give you undefined

see example below

  const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined

We can replace this old syntax

if (response && response.data && response.data.someData && response.data.someData.someMoreData) {}

with this neater syntax

if( response?.data?.someData?.someMoreData) {}

This syntax is not supported in IE, Opera, safari & samsund android

for more detail you can check this URL

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Hanzla Habib
  • 3,457
  • 25
  • 25
2

Also, the same things can be written shorter:

if (!variable){
    // Do it if the variable is undefined
}

or

if (variable){
    // Do it if the variable is defined
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
raskalbass
  • 740
  • 4
  • 21
  • 2
    Your first case can be triggered by defined variable. For example if variable = 0, !variable will trigger. So your answer is quite wrong. – Stranded Kid Jul 10 '15 at 09:44
  • I think just wrong wording, I think he meant "do it if variable is undefined or another falsy value" which is often the logic that people are looking for. – Ynot May 12 '17 at 02:54
  • @Ynot - `!variable` would be true is `variable` is undefined, or *is defined* and happens to be equal to **0**, **false**, *etc*. I don't see how that's either an answer to OP's question, or remotely useful. – Scott Smith Apr 20 '18 at 05:13
  • I did not upvote this because I didn't think it was the best answer. I thought Stranded Kid brought up a good point but that he mischaracterized the solution. Just because you can imagine a use case where something is wrong doesn't mean there exists no use case where it is right. It is directly related to the OP's question in that, if you understand the implications then this can be used without issue to check if a property is undefined (|| false). e.g. checking a flag `if (myobject.isFeatureEnabled) {` – Ynot Apr 21 '18 at 07:01
2

Use:

To check if property is undefined:

if (typeof something === "undefined") {
    alert("undefined");
}

To check if property is not undefined:

if (typeof something !== "undefined") {
    alert("not undefined");
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mike Clark
  • 1,860
  • 14
  • 21
2

I'm assuming you're going to also want to check for it being either undefined or null. If so, I suggest:

myVar == null

This is one of the only times a double equals is very helpful as it will evaluate to true when myVar is undefined or null, but it will evaluate to false when it is other falsey values such as 0, false, '', and NaN.

This the actual the source code for Lodash's isNil method.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
IliasT
  • 3,973
  • 1
  • 24
  • 26
2

A simple way to check if a key exists is to use in:

if (key in obj) {
  // Do something
} else {
  // Create key
}

const obj = {
  0: 'abc',
  1: 'def'
}

const hasZero = 0 in obj

console.log(hasZero) // true
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CodeDraken
  • 1,163
  • 6
  • 12
  • As the OP is specifically asking about if a property in an object is defined, this is now the most direct and straightforward answer for anybody using modern JavaScript. – bjg222 Sep 12 '19 at 15:25
1

I'm surprised I haven't seen this suggestion yet, but it gets even more specificity than testing with typeof. Use Object.getOwnPropertyDescriptor() if you need to know whether an object property was initialized with undefined or if it was never initialized:

// to test someObject.someProperty
var descriptor = Object.getOwnPropertyDescriptor(someObject, 'someProperty');

if (typeof descriptor === 'undefined') {
  // was never initialized
} else if (typeof descriptor.value === 'undefined') {
  if (descriptor.get || descriptor.set) {
    // is an accessor property, defined via getter and setter
  } else {
    // is initialized with `undefined`
  }
} else {
  // is initialized with some other value
}
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
1

Introduced in ECMAScript 6, we can now deal with undefined in a new way using Proxies. It can be used to set a default value to any properties which doesn't exist so that we don't have to check each time whether it actually exists.

var handler = {
  get: function(target, name) {
    return name in target ? target[name] : 'N/A';
  }
};

var p = new Proxy({}, handler);
p.name = 'Kevin';
console.log('Name: ' +p.name, ', Age: '+p.age, ', Gender: '+p.gender)

Will output the below text without getting any undefined.

Name: Kevin , Age: N/A , Gender: N/A
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Krishnadas PC
  • 5,981
  • 2
  • 53
  • 54
0

This is probably the only explicit form of determining if the existing property-name has an explicit and intended value of undefined; which is, nonetheless, a JavaScript type.

"propertyName" in containerObject && ""+containerObject["propertyName"] == "undefined";
>> true \ false

This expression will only return true if the property name of the given context exists (truly) and only if its intended value is explicitly undefined.

There will be no false positives like with empty or blank strings zeros nulls or empty arrays and alike. This does exactly that. Checks i.e., makes sure the property name exists (otherwise it would be a false positive), than it explicitly checks if its value is undefined e.g. of an undefined JavaScript type in it's string representation form (literally "undefined") therefore == instead of === because no further conversion is possible. And this expression will only return true if both, that is all conditions are met. E.g. if the property-name doesn't exist, - it will return false. Which is the only correct return since nonexistent properties can't have values, not even an undefined one.

Example:

containerObject = { propertyName: void "anything" }
>> Object { propertyName: undefined }

// Now the testing

"propertyName" in containerObject && ""+containerObject["propertyName"] == "undefined";
>> true

/* Which makes sure that nonexistent property will not return a false positive
 * unless it is previously defined  */

"foo" in containerObject && ""+containerObject["foo"] == "undefined";
>> false
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26
  • And what if the property has the *string* value `"undefined"`? ...as in `containerObject = { propertyName: "undefined" }` –  Dec 18 '17 at 13:57
  • lol, ok then... you'll get the exact false positive that you claim your code prevents. https://jsfiddle.net/pfwx5j51/ –  Dec 21 '17 at 14:30
  • ...also, with your code `==` and `===` will behave identically because you're always comparing matching types. So that distinction is immaterial. –  Dec 21 '17 at 14:35
  • @rockstar Exactly, - you don't need a static comparison operator on arguments of the same type. That'd be an overkill. Furthermore if the value of a property is a string of undefined, or a type of undefined, doesn't change a thing. Because they both have the same meaning and equal yield. You can spare yourself a few bits in assigning "undefined" as a property value. That's an overkill Because you will be able to retrieve a string of undefined without having to assign it. I agree - technically you may consider it a 'false positive' - but practically & empirically, it is not. Thanks anyway. – Bekim Bacaj Dec 21 '17 at 22:48
  • On arguments of the same type, the `===` and `==` do the exact same work. When the types don't match the `==` does *more* work, so calling `===` "overkill" makes little sense, as it always provides an equal or simpler algorithm. –  Dec 21 '17 at 23:11
  • The `undefined` and `"undefined"` have the same meaning only in your test, which is what makes it a false positive, since your test's objective is to find exactly that kind of distinction. So it's a clear fail, and would be needlessly complex anyway since `("prop" in obj) && obj.prop === undefined` is simpler and is actually correct. Yep, you're welcome. –  Dec 21 '17 at 23:12
  • @rockstar you false positive case is never the case. And when it is - it is deliberate and therefore equal, but if you feel that strong about it feel free to edit my answer. – Bekim Bacaj Dec 21 '17 at 23:15
  • I'm not sure what you mean when you say it's deliberate and therefore equal. One can have the string value `"undefined"` for many different reasons, so unless there's a highly unusual situation, the string `"undefined"` should be just as distinct from the value `undefined` as the string `"foobar"` is. –  Dec 21 '17 at 23:23
  • That's the point, I'm not being able to to see any other reason of assigning an undefined value as a string, except to use this value a a word meaning undefined in some readable text and therefore it's an overkill because there's no need to actually write it in order to be able to retrieve it. p.s === is an overkill in JS when dealing with same type args because JS is dynamic by birth, not by extension. Strictness needs to be forced on it. Anyway, you are most welcome to correct my mistake. That way it will take your signature. – Bekim Bacaj Dec 21 '17 at 23:43
  • It's a pretty common misconception that the `===` has to do more work because of JS's dynamic nature, but it actually has to do less, because when the types don't match, it's able to [return `false` immediately](https://tc39.github.io/ecma262/#sec-strict-equality-comparison) instead of entering into a recursive coercion algorithm. It's the type coercion that needs to be forced, which is what `==` does when the types don't match. When they do match, `==` and `===` [use identical algorithms](https://tc39.github.io/ecma262/#sec-abstract-equality-comparison). –  Dec 22 '17 at 00:12
  • ...As to `undefined`, it's probably pretty rare to have that as an explicit value anyway, but if one is checking for it, then they probably use it for a reason (though `null` is arguably better). In that case, I think they'd want to ensure a distinction. Anyway, just pointing out that it can conflict with the intent in those cases. –  Dec 22 '17 at 00:12
  • Don't ever use null for what it's not. – Bekim Bacaj Dec 28 '17 at 17:20
  • Oh, don't worry, I won't. That's why I say it's arguably better than `undefined` to represent a *defined* property that doesn't have a useful value. –  Dec 28 '17 at 18:45
0

You can use the JavaScript object function like this:

var ojb ={
    age: 12
}

if(ojb.hasOwnProperty('name')){
    console.log('property exists and is not undefined');
}

The above method returns true if it got that property or the property is not undefined.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

There are a few little helpers in the Lodash library:

isUndefined - to check if value is undefined.

_.isUndefined(undefined) // => true
_.isUndefined(null) // => false

has - to check if object contains a property

const object = { 'a': { 'b': 2 } }

_.has(object, 'a.b') // => true
_.has(object, 'a.c') // => false
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aliaksandr Sushkevich
  • 11,550
  • 7
  • 37
  • 44
0

Review

A lot of the given answers give a wrong result because they do not distinguish between the case when an object property does not exist and the case when a property has value undefined. Here is proof for most popular solutions:

let obj = {
  a: 666,
  u: undefined // The 'u' property has value 'undefined'
               // The 'x' property does not exist
}

console.log('>>> good results:');
console.log('A', "u" in obj, "x" in obj);
console.log('B', obj.hasOwnProperty("u"),      obj.hasOwnProperty("x"));

console.log('\n>>> bad results:');
console.log('C', obj.u === undefined,          obj.x === undefined);
console.log('D', obj.u == undefined,           obj.x == undefined);
console.log('E', obj["u"] === undefined,       obj["x"] === undefined);
console.log('F', obj["u"] == undefined,        obj["x"] == undefined);
console.log('G', !obj.u,                      !obj.x);
console.log('H', typeof obj.u === 'undefined', typeof obj.x === 'undefined');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
0

Version for the use of dynamic variables Did you know?

var boo ='lala';

function check(){
  if(this['foo']){
        console.log('foo is here');}
  else{
        console.log('have no foo');
      }

  if(this['boo']){
        console.log('boo is here');}
  else{
        console.log('have no boo');
      }
}

check();
Adam111p
  • 3,469
  • 1
  • 23
  • 18
0

handle undefined

function isUndefined(variable,defaultvalue=''){

    if (variable == undefined ) return defaultvalue;
    
    return variable;

}

var obj={
und:undefined,
notundefined:'hi i am not undefined'
}


function isUndefined(variable,defaultvalue=''){

    if (variable == undefined )
    { 
        return defaultvalue;
    }
    return variable

}

console.log(isUndefined(obj.und,'i am print'))
console.log(isUndefined(obj.notundefined,'i am print'))
Balaji
  • 9,657
  • 5
  • 47
  • 47
-1

I found this article 7 Tips to Handle undefined in JavaScript

which is showing really interesting things about undefined like:

The existence of undefined is a consequence of JavaScript’s permissive nature that allows the usage of:

  • uninitialized variables
  • non-existing object properties or methods
  • out of bounds indexes to access array elements
  • the invocation result of a function that returns nothing
Ravi Makwana
  • 2,782
  • 1
  • 29
  • 41
-1

In JavaScript, there are truthy and falsy expressions. If you want to check if the property is undefined or not, there is a straight way of using an if condition as given,

  1. Using truthy/falsy concept.
if(!ob.someProp){
    console.log('someProp is falsy')
}

However, there are several more approaches to check the object has property or not, but it seems long to me. Here are those.

  1. Using === undefined check in if condition
if(ob.someProp === undefined){
    console.log('someProp is undefined')
}
  1. Using typeof

typeof acts as a combined check for the value undefined and for whether a variable exists.

if(typeof ob.someProp === 'undefined'){
    console.log('someProp is undefined')
}
  1. Using hasOwnProperty method

The JavaScript object has built in the hasOwnProperty function in the object prototype.

if(!ob.hasOwnProperty('someProp')){
    console.log('someProp is undefined')
}

Not going in deep, but the 1st way looks shortened and good to me. Here are the details on truthy/falsy values in JavaScript and undefined is the falsy value listed in there. So the if condition behaves normally without any glitch. Apart from the undefined, values NaN, false (Obviously), '' (empty string) and number 0 are also the falsy values.

Warning: Make sure the property value does not contain any falsy value, otherwise the if condition will return false. For such a case, you can use the hasOwnProperty method

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
  • ... do you also check the code examples you are posting ?... e.g ... `if (typeof ob.someProp === undefined) { ...` – Peter Seliger May 12 '20 at 14:20
  • 1
    ... you also can not nonchalantly "fix/patch" your provided examples that are answering how to check for an undefined property by exclaiming a **Warning** afterwards ... actually `if (!ob.someProp) { console.log('someProp is undefined'); }` from the beginning has to be implemented as `if (!ob.someProp) { console.log('someProp is falsy'); }` – Peter Seliger May 12 '20 at 14:25
  • @PeterSeliger Thanks for noticing that. – Kiran Maniya May 12 '20 at 14:47
  • I also was pointing to your No.3 / typeof example ... it is still implemented wrong ... it should be ... `if (typeof ob.someProp === 'undefined') {` ... your code does not compare against a string value but against the undefined value. Thats why the question about if you do actually test before you post. – Peter Seliger May 13 '20 at 21:26
  • @PeterSeliger Thanks again for noticing, well' I wrote this directly into the post so it's susceptible to error. I would have fiddle before posting. Correcting is done – Kiran Maniya May 14 '20 at 07:24
-2

Object.hasOwnProperty(o, 'propertyname');

This doesn't look up through the prototype chain, however.

ember arlynx
  • 3,129
  • 2
  • 20
  • 22
  • 2
    `Object.hasOwnProperty` won't work as expected; it checks if the `Object` object has a property with the name contained in `o`. You probably mean `Object.prototype.hasOwnProperty.call(o, 'propertyname')`. – icktoofay May 14 '13 at 02:59
-21
if (somevariable == undefined) {
  alert('the variable is not defined!');
}

You can also make it into a function, as shown here:

function isset(varname){
  return(typeof(window[varname]) != 'undefined');
}
tslocum
  • 3,422
  • 5
  • 30
  • 33
  • 16
    First, when somevariable equals undefined, it doesn't mean the variable is undefined - it's just the value that is undefined. When the variable is undefined, then this code will throw an error. Second, this isset function will only work for global variables. – Rene Saarsoo Jan 26 '10 at 23:09
  • 1
    what about local variables? strange trick with window[variable] – Denis Aug 27 '13 at 13:09