32

Possible Duplicate:
How do I check to see if an object has an attribute in Javascript?

I have a Javascript object defined as following:

var mmap = new Object();

mmap['Q'] = 1;
mmap['Z'] = 0;
mmap['L'] = 7;
...

How to check whether this map has a value for a given key (for example 'X')? Does .hasOwnProperty() get into play?

Community
  • 1
  • 1
Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
  • Why not `hasOwnProperty`? (Excepting aesthetic reasons.) The difference between that an `in` is that `in` will traverse the [[prototype]] as well. –  May 30 '12 at 19:36
  • 1
    `mmap.has(key)` is latest ECMAScript 6 way of checking the existance of a key in a map. [Refer to this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has) for complete details. – Diablo May 30 '17 at 08:59

2 Answers2

59
if ('X' in mmap)
{
    // ...
}

Here is an example on JSFiddle.

hasOwnProperty is also valid, but using in is much more painless. The only difference is that in returns prototype properties, whereas hasOwnProperty does not.

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
10

You can use:

(mmap['X'] === undefined)

Fiddle: http://jsfiddle.net/eDTrY/

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326