How to Check if an Object Has a Specific Property in Javascript

You are currently viewing How to Check if an Object Has a Specific Property in Javascript

How to Check if an Object has a Specific Property in JavaScript

var obj = {
    a: undefined,
    b: null,
    c: false
};
 
// a, b, c all found
for ( var prop in obj ) {
    document.writeln( "Object1: " + prop );
}
 
function Class(){
    this.a = undefined;
    this.b = null;
    this.c = false;
}
 
Class.prototype = {
    a: undefined,
    b: true,
    c: true,
    d: true,
    e: true
};
 
var obj2 = new Class();
 
// a, b, c, d, e found
for ( var prop in obj2 ) {
    document.writeln( "Object2: " + prop );
}
 
function hasOwnProperty(obj, prop) {
    var proto = obj.__proto__ || obj.constructor.prototype;
    return (prop in obj) &&
        (!(prop in proto) || proto[prop] !== obj[prop]);
}
 
if ( Object.prototype.hasOwnProperty ) {
    var hasOwnProperty = function(obj, prop) {
        return obj.hasOwnProperty(prop);
    }
}
 
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
    if ( hasOwnProperty(obj2, prop) ) {
        document.writeln( "Object2 w/ hasOwn: " + prop );
    }
}

_.<span class="hljs-title function_">has</span>(x, <span class="hljs-string">'key'</span>);
 

<span class="hljs-keyword">function</span> <span class="hljs-title function_">has</span>(<span class="hljs-params">object, key</span>) {
  <span class="hljs-keyword">return</span> object ? hasOwnProperty.<span class="hljs-title function_">call</span>(object, key) : <span class="hljs-literal">false</span>;
}
<span class="hljs-comment">// hasOwnProperty = Object.prototype.hasOwnProperty</span>

var x = {
  'key': 1
};
 
if ('key' in x) {
  console.log('has');
}

if (x.key !== undefined)
Armin Ronacher seems to have already beat me to it, but:
 
Object.prototype.hasOwnProperty = function(property) {
    return this[property] !== undefined;
};
 
x = {'key': 1};
 
if (x.hasOwnProperty('key')) {
    alert('have key!');
}
 
if (!x.hasOwnProperty('bar')) {
    alert('no bar!');
}
A safer, but slower solution, as pointed out by Konrad Rudolph and Armin Ronacher would be:
 
Object.prototype.hasOwnProperty = function(property) {
    return typeof this[property] !== 'undefined';
};

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply