Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a key exists in a JavaScript object?

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?

like image 367
Adam Ernst Avatar asked Jul 08 '09 13:07

Adam Ernst


People also ask

How do you check if a key is in a object JavaScript?

Use the in operator to check if a key exists in an object, e.g. "key" in myObject . The in operator will return true if the key is present in the object, otherwise false is returned. Copied! The syntax used with the in operator is: string in object .

How do you check if a key value pair exists in an object JavaScript?

Using the in Operator The in operator in JavaScript is used to determine if a certain property exists in an object or its inherited properties (also known as its prototype chain). If the provided property exists, the in operator returns true.

How do you check if a key exists in an array of objects JavaScript?

indexOf() method. That method would return the numerical index of a specified value (an object key, in our case) if that value is indeed present in the array upon which indexOf() is called (or it will return -1 if the specified value/key does not exist within the array).

How do you check key is exist or not?

Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.


2 Answers

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

like image 166
Ates Goral Avatar answered Sep 28 '22 11:09

Ates Goral


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

http://jsperf.com/checking-if-a-key-exists-in-a-javascript-array

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.

like image 34
rdllopes Avatar answered Sep 28 '22 10:09

rdllopes