By Matt Sheppard


2008-08-26 07:25:08 8 Comments

What's the best way of checking if an object property in JavaScript is undefined?

30 comments

@Alireza 2017-05-24 14:15:55

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

@Przemek Struciński 2019-09-27 06:56:09

ES2019 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 phone property only when user and contactDetails are defined.

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

@lzl124631x 2016-01-14 05:43:53

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;
}

@Erwin 2009-01-06 12:27:41

Use:

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

If an object variable which have some properties you can use same thing like this:

if (typeof my_obj.someproperties === "undefined"){
    console.log('the property is not available...'); // print into console
}

@neu-rah 2012-06-25 19:20:54

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.

@Zack 2012-09-24 19:01:30

@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? jsfiddle.net/djH9N/6

@drzaus 2013-01-13 17:45:46

see my answer below for a comparison of the different "solutions" stackoverflow.com/a/14306293/1037948

@pnkfelix 2013-02-15 15:08:05

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

@Ry- 2014-05-14 03:05:48

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.

@Bruno Buccolo 2016-03-15 20:50:43

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. codereadability.com/how-to-check-for-undefined-in-javascript

@cdhowie 2017-12-01 16:50:32

@pnkfelix If you need to test if a variable is declared then you are doing something very wrong in your code. There should never be a case where you need to support this.

@user1032531 2017-12-14 12:41:40

@Ryan what "other answer"?

@Ry- 2017-12-14 20:02:20

@user1032531: I’d recommend mine

@Headbank 2019-02-28 15:05:28

@cdhowie Is it wrong to write a function with optional arguments? I'm not aware of any other way a function can check whether a given argument has been passed to it or not.

@cdhowie 2019-03-02 22:36:22

@Headbank The variable is declared in that case, so arg === undefined works fine.

@blackmiaool 2017-10-28 09:24:12

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, 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 input value to string to compare with "undefined" and ensure it's negative value.

isUndefined3:

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

@CodeDraken 2018-09-11 12:23:56

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

@bjg222 2019-09-12 15:25:53

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.

@Krishnadas PC 2018-07-23 12:10:48

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

@Aliaksandr Sushkevich 2018-04-07 11:16:15

There are a few little helpers in 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

@Aditya Vashishtha 2018-03-07 18:15:25

You can use the Javascript Object function like this:

var ojb ={
    age:12
}

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

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

@Sarkis Arutiunian 2018-03-21 16:50:26

you can also use Proxy, it will work with nested calls, but 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 someting
}

@Ry- 2014-02-26 21:17:10

Despite being vehemently recommended by many other answers here, 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. There’s a lot more to this. undefined is not a keyword in JavaScript. Instead, it’s a property on the global object with the Undefined value. However, since ES5, this property has been read-only and non-configurable. No modern browser will allow the undefined property to be changed, and as of 2017 this has been the case for a long time. Lack of strict mode doesn’t affect undefined’s behaviour either – it just makes statements like undefined = 5 do nothing instead of throwing. Since it isn’t a keyword, though, you can declare variables with the name undefined, and those variables could be changed, making this once-common pattern:

    (function (undefined) {
        // …
    })()
    

    more dangerous than using the global undefined. If you have to be ES3-compatible, replace undefined with void 0 – don’t resort to typeof. (void has always been a unary operator that evaluates to the Undefined value for any operand.)

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. substitute void 0 otherwise.

@blgt 2014-03-25 14:32:41

@BenjaminGruenbaum True but completely misleading. Any non-default context can define its own undefined, hiding the default one. Which for most practical purposes has the same effect as overwriting it.

@Benjamin Gruenbaum 2014-03-25 14:41:18

@blgt That's paranoid and irrelevant for anything practical. Every context can override console.log, redefine Array prototype methods, and even override Function.prototype.call` hooking, and altering every time you call a function in JavaScript. Protecting against this is very paranoid and rather silly. Like I (and minitech) said, you can use void 0 to compare against undefined but again - that's silly and overkill.

@Simon Baumgardt-Wellander 2018-02-20 19:37:04

I wish I had more than one upvote to give. This is the most correct answer. I really wanna stop seeing typeof something === "undefined") in code.

@wizzwizz4 2018-04-11 18:31:46

@BenjaminGruenbaum For lazy programmers, void 0 is (for once) both shorter and safer! That's a win in my book.

@Patrick Michaelsen 2019-04-10 20:40:00

This really should be the accepted answer. It is the most thorough and up-to-date.

@MarkPflug 2010-08-23 18:03:18

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.

@Enrique 2011-12-19 18:27:14

+1 for noting that myVar === undefined will raise an error if myVar was not declared

@Codebeat 2012-11-08 06:49:44

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.

@Mark Amery 2013-01-13 19:05:13

I find the first justification given here for not using === undefined bewildering. Yes, you can assign to undefined, but there is no legitimate reason to do so, and it's predictable that doing so may break your code. In C you can #define true false, and in Python you can assign to True and False, but people don't feel the need to design their code in those languages in such a way as to protect against the possibility of themselves deliberately sabotaging their own environment elsewhere in the code. Why is the possibility of assigning to undefined even worth considering here?

@Kevin Meredith 2013-07-05 16:17:52

What about if(typeof myVar != "undefined"). Is the "!=" acceptable?

@eis 2013-08-20 15:12:13

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?

@Ingo Bürk 2013-08-23 22:00:16

@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 !=.

@Claudiu 2013-10-03 17:45:42

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.

@user247702 2014-02-07 14:09:05

In modern browsers (FF4+, IE9+, Chrome unknown), it's no longer possible to modify undefined. MDN: undefined

@rojobuffalo 2015-01-16 19:18:05

fiddle for demonstration of this point

@dharcourt 2015-10-02 19:12:09

@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.

@Stijn de Witt 2015-11-01 12:53:40

@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.

@Zero3 2015-12-15 15:38:04

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.

@Codebeat 2016-11-23 05:16:47

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.

@Velu S Gautam 2017-07-25 12:36:24

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. ecma-international.org/ecma-262/5.1/#sec-15.1.1.3

@Atav32 2017-07-31 13:02:45

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.

@Ry- 2017-08-16 00:17:19

@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”.

@user8897421 2017-12-18 13:39:38

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.

@IliasT 2017-06-15 00:16:30

I'm assuming your 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 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.

@IliasT 2018-02-09 18:33:41

Surprised this hasn't gotten more upvotes or comments. What do people think about this?

@Bekim Bacaj 2017-04-20 19:01:28

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 JS 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 undefined JS 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

@user8897421 2017-12-18 13:57:36

And what if the property has the string value "undefined"? ...as in containerObject = { propertyName: "undefined" }

@user8897421 2017-12-21 14:30:22

lol, ok then... you'll get the exact false positive that you claim your code prevents. jsfiddle.net/pfwx5j51

@user8897421 2017-12-21 14:35:18

...also, with your code == and === will behave identically because you're always comparing matching types. So that distinction is immaterial.

@Bekim Bacaj 2017-12-21 22:48:10

@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.

@user8897421 2017-12-21 23:11:41

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.

@user8897421 2017-12-21 23:12:19

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.

@Bekim Bacaj 2017-12-21 23:15:55

@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.

@user8897421 2017-12-21 23:23:38

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.

@Bekim Bacaj 2017-12-21 23:43:54

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.

@user8897421 2017-12-22 00:12:16

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

@user8897421 2017-12-22 00:12:21

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

@Bekim Bacaj 2017-12-28 17:20:54

Don't ever use null for what it's not.

@user8897421 2017-12-28 18:45:14

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.

@Patrick Roberts 2017-03-28 00:03:33

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
}

@Marian Klühspies 2016-03-03 10:05:36

There is a nice & 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 config 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

@Codebeat 2011-08-12 14:40:24

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)

@Mike Clark 2015-08-14 11:34:02

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");
}

@Konstantin Smolyanin 2013-08-08 20:28:22

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 2013-09-11 10:53:06

@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 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.

@Bergi 2013-09-11 11:00:10

It didn't need extra documentation since it's in the EcmaScript spec, which also says that [[Enumerable]] is false :-)

@hlovdal 2014-10-24 11:01:21

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.

@Ry- 2018-04-11 21:38:27

@hlovdal: That’s totally pointless vs. obj.prop === undefined.

@Frank Nocke 2018-06-11 08:46:50

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.

@Val 2015-03-06 15:58:00

I use if (this.variable) to test if it is defined. Simple if (variable), recommended above, fails for me. It turns out that it works only when 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 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.

@Travis 2015-02-15 03:10:11

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");
}

@Stijn de Witt 2015-11-01 02:24:40

I think you can replace the last example with if (!obj.prop)

@Travis 2017-04-07 14:31:02

@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

@Patrick Roberts 2017-06-15 18:40:32

var obj = {foo: undefined}; obj.foo === void 0 -> true. How is that "never defined as undefined"? This is wrong.

@Vitalii Fedorenko 2014-12-14 22:35:24

If you are using Angular:

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

Underscore.js:

_.isUndefined(obj) 
_.isUndefined(obj.prop) 

@Stijn de Witt 2015-11-01 02:43:00

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)

@DenisS 2014-02-10 16:26:05

'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.

@Stijn de Witt 2015-11-01 02:28:23

But what if you run in Node? typeof history != 'undefined' actually works in both systems.

@Seti 2014-10-09 08:09:08

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.

@Angelin Nadar 2014-07-08 08:19:07

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;

@Henry Heleine 2014-12-09 22:12:18

jQuery will also take care of any cross-browser compatibility issues with the different JavaScript APIs.

@Marthijn 2013-12-19 10:44:47

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;
}

@RobG 2014-04-01 01:16:48

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

@Brian M. Hunt 2015-09-14 13:08:09

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.

@Stijn de Witt 2015-11-01 02:41:45

isUndefined(obj): 16 chars. obj === void 0: 14 chars. 'nough said.

@Anoop 2011-10-17 11:22:52

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

@icktoofay 2013-05-14 03:02:21

While it won't affect the validity of your code, you've got a typo: getUndefiend should be getUndefined.

@Ricky 2008-08-26 12:38:22

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

@clacke 2010-07-30 08:49:32

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.

@Simon East 2011-06-15 00:22:35

Wrong. This throws an error if the variable has not been created. Should not be voted up. Use typeof instead.

@Juan Garcia 2014-06-18 05:21:23

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 is buried in wrong answers >_<

So, for anyone who pass by, I will give you undefineds 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

@raskalbass 2014-06-16 12:15:57

Also same things can be written shorter:

if (!variable){
    //do it if variable is Undefined
}

or

if (variable){
    //do it if variable is Defined
}

@Stranded Kid 2015-07-10 09:44:27

Your first case can be triggered by defined variable. For example if variable = 0, !variable will trigger. So your answer is quite wrong.

@Ynot 2017-05-12 02:54:10

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.

@Scott Smith 2018-04-20 05:13:37

@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.

@Ynot 2018-04-21 07:01:45

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) {

Related Questions

Sponsored Content

89 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6168636 View
  • 7693 Score
  • 89 Answer
  • Tags:   javascript arrays

20 Answered Questions

[SOLVED] Checking if a key exists in a JavaScript object?

  • 2009-07-08 13:21:32
  • Adam Ernst
  • 1827510 View
  • 2766 Score
  • 20 Answer
  • Tags:   javascript object

41 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

38 Answered Questions

[SOLVED] Length of a JavaScript object

69 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

47 Answered Questions

28 Answered Questions

[SOLVED] Iterate through object properties

3 Answered Questions

38 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

Sponsored Content