4137

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?

4
  • 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. Commented 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. Commented Oct 24, 2016 at 19:05
  • 4
    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 Commented Oct 24, 2018 at 8:22
  • Just a warning to those coming to this in 2022 -- MalwareBytes throws warnings at the "benchmark" link posted by @EscapeNetscape above. It might have been ok in 2016 when posted -- I suggest avoiding it now. Commented Nov 20, 2022 at 0:04

33 Answers 33

1
2
0

I do it as following

const obj = { a: 1, b: 2, c: 3 };

// Using the 'in' operator
console.log('a' in obj); // true
console.log('d' in obj); // false

// Using the 'hasOwnProperty' method
console.log(obj.hasOwnProperty('b')); // true
console.log(obj.hasOwnProperty('d')); // false
Sign up to request clarification or add additional context in comments.

Comments

-1

New awesome solution with JavaScript Destructuring:

let obj = {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3",
};

let {key1, key2, key3, key4} = obj;

// key1 = "value1"
// key2 = "value2"
// key3 = "value3"
// key4 = undefined

// Can easily use `if` here on key4
if(!key4) { console.log("key not present"); } // Key not present

Do check other use of JavaScript Destructuring

Comments

-1

A fast and easy solution is to convert your object to json then you will be able to do this easy task:

const allowed = {
    '/login' : '',
    '/register': '',
    '/resetpsw': ''
};
console.log('/login' in allowed); //returns true

If you use an array the object key will be converted to integers ex 0,1,2,3 etc. therefore, it will always be false

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.