Categories
arrays javascript object

Checking if a key exists in a JavaScript object?

3760

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?

3

  • 2

    Everything (almost everything) in JavaScript is an Object or can be cast as one. This is where pseudo associative arrays are born just like @PatrickM pointed out.

    Jan 3, 2013 at 18:50


  • this benchmark jsben.ch/#/WqlIl gives you an overview over the most common ways how to achieve this check.

    Oct 24, 2016 at 19:05

  • 3

    a quick workaround, usually I go for property.key = property.key || 'some default value', just in case I want that key to exist with some value to it

    – RGLSV

    Oct 24, 2018 at 8:22

5168

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

4

  • 316

    I’m convinced that there are use cases for having properties intentionally set to undefined.

    Jul 8, 2009 at 16:12

  • 182

    Valid use case: Gecko 1.9.1 [Firefox 3.5] has no window.onhashchange property. Gecko 1.9.2 [Firefox 3.6] has this property set to undefined (until the hash changes). To feature detect the hash history or the browser version, one must use window.hasOwnProperty(“onhashchange”);

    – SamGoody

    Feb 12, 2010 at 10:45

  • 10

    Random fact: properties set to undefined won’t get serialized by JSON.stringify(...), whereas null does. So anything set to undefined that is round tripped to JSON will simply disappear. You can also use delete obj.propName to remove a property from an object.

    Jul 15, 2021 at 4:37

  • The benchmark has completely different results for me. Shouldn’t it be updated? (Also please describe your images better than “Benchmark results”, this is useless for a person who needs the alt text because they can’t see the image.)

    – Laurel

    Jun 9 at 12:42

354

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

http://www.ecma-international.org/ecma-262/5.1/#sec-8.10

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!

Benchmark

https://jsben.ch/HaHQt

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.

Compare:

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

Advice

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.

EDIT: 12/04/2018 – NOT RELEVANT ANYMORE

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.

0

    180

    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
    }
    

    3

    • Yes. It returns undefined whether it is created as an object or an array.

      – Nosredna

      Jul 8, 2009 at 13:30

    • 9

      What if the key exists but the value is actually undefined?

      Jul 8, 2009 at 15:52

    • 18

      You should use === instead of == when comparing to undefined, otherwise null will compare equal to undefined.

      Jul 8, 2009 at 15:56