arrays - Checking if a key exists in a JavaScript object?

ID : 124

viewed : 185

Tags : javascriptarraysobjectjavascript

Top 5 Answer for arrays - Checking if a key exists in a JavaScript object?

vote vote


Checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?

var obj = { key: undefined }; console.log(obj["key"] !== undefined); // false, but the key exists!

You should instead use the in operator:

var obj = { key: undefined }; console.log("key" in obj); // true, regardless of the actual value

If you want to check if a key doesn't exist, remember to use parenthesis:

var obj = { not_key: undefined }; console.log(!("key" in obj)); // true if "key" doesn't exist in object console.log(!"key" in obj);   // Do not do this! It is equivalent to "false in obj"

Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty:

var obj = { key: undefined }; console.log(obj.hasOwnProperty("key")); // true

For performance comparison between the methods that are in, hasOwnProperty and key is undefined, see this benchmark:

Benchmark results

vote vote


Quick Answer

How do I check if a particular key exists in a JavaScript object or array? If a key doesn't exist and I try to access it, will it return false? Or throw an error?

Accessing directly a missing property using (associative) array style or object style will return an undefined constant.

The slow and reliable in operator and hasOwnProperty method

As people have already mentioned here, you could have an object with a property associated with an "undefined" constant.

 var bizzareObj = {valid_key:  undefined}; 

In that case, you will have to use hasOwnProperty or in operator to know if the key is really there. But, but at what price?

so, I tell you...

in operator and hasOwnProperty are "methods" that use the Property Descriptor mechanism in Javascript (similar to Java reflection in the Java language).

The Property Descriptor type is used to explain the manipulation and reification of named property attributes. Values of the Property Descriptor type are records composed of named fields where each field’s name is an attribute name and its value is a corresponding attribute value as specified in 8.6.1. In addition, any field may be present or absent.

On the other hand, calling an object method or key will use Javascript [[Get]] mechanism. That is a far way faster!


Comparing key access in JS.

Using in operator
var result = "Impression" in array; 

The result was

12,931,832 ±0.21% ops/sec      92% slower  
Using hasOwnProperty
var result = array.hasOwnProperty("Impression") 

The result was

16,021,758 ±0.45% ops/sec     91% slower 
Accessing elements directly (brackets style)
var result = array["Impression"] === undefined 

The result was

168,270,439 ±0.13 ops/sec     0.02% slower  
Accessing elements directly (object style)
var result = array.Impression  === undefined; 

The result was

168,303,172 ±0.20%     fastest 

EDIT: What is the reason to assign to a property the undefined value?

That question puzzles me. In Javascript, there are at least two references for absent objects to avoid problems like this: null and undefined.

null is the primitive value that represents the intentional absence of any object value, or in short terms, the confirmed lack of value. On the other hand, undefined is an unknown value (not defined). If there is a property that will be used later with a proper value consider use null reference instead of undefined because in the initial moment the property is confirmed to lack value.


var a = {1: null};  console.log(a[1] === undefined); // output: false. I know the value at position 1 of a[] is absent and this was by design, i.e.:  the value is defined.  console.log(a[0] === undefined); // output: true. I cannot say anything about a[0] value. In this case, the key 0 was not in a[]. 


Avoid objects with undefined values. Check directly whenever possible and use null to initialize property values. Otherwise, use the slow in operator or hasOwnProperty() method.


As people have commented, modern versions of the Javascript engines (with firefox exception) have changed the approach for access properties. The current implementation is slower than the previous one for this particular case but the difference between access key and object is neglectable.

vote vote


It will return undefined.

var aa = {hello: "world"};  alert( aa["hello"] );      // popup box with "world"  alert( aa["goodbye"] );    // popup box with "undefined"

undefined is a special constant value. So you can say, e.g.

// note the three equal signs so that null won't be equal to undefined if( aa["goodbye"] === undefined ) {     // do something } 

This is probably the best way to check for missing keys. However, as is pointed out in a comment below, it's theoretically possible that you'd want to have the actual value be undefined. I've never needed to do this and can't think of a reason offhand why I'd ever want to, but just for the sake of completeness, you can use the in operator

// this works even if you have {"goodbye": undefined} if( "goodbye" in aa ) {     // do something } 
vote vote


"key" in obj 

Is likely testing only object attribute values that are very different from array keys

vote vote


The accepted answer refers to Object. Beware using the in operator on Array to find data instead of keys:

("true" in ["true", "false"]) // -> false (Because the keys of the above Array are actually 0 and 1) 

To test existing elements in an Array: Best way to find if an item is in a JavaScript array?

Top 3 video Explaining arrays - Checking if a key exists in a JavaScript object?