DEV Community

James L
James L

Posted on

πŸŽ„ JS Advent #3 - Object.hasOwnProperty()πŸŽ„

For the month of December I have challenged myself to write 24 articles about JS up until Xmas.

The third installment in this series is about Object.hasOwnProperty().

Object.hasOwnProperty() returns a boolean value if the provided property is present on the calling Object.

Example:

let obj = { name: 'Sarah', age: 20 };
console.log(obj.hasOwnProperty(name)); // true
console.log(obj.hasOwnProperty(job)); // false
Enter fullscreen mode Exit fullscreen mode

Will still return true even if the value is null or undefined:

obj.property = undefined;
obj.anotherProperty = null;
console.log(obj.hasOwnProperty(property)); // true
console.log(obj.hasOwnProperty(anotherProperty)); // true
Enter fullscreen mode Exit fullscreen mode
hasOwnProperty vs in vs dot/bracket notation

You can also check for a property on an object using the in operator or by using dot/bracket notation.

name in obj // true
!!obj.name // true
!!obj["name"] // true
Enter fullscreen mode Exit fullscreen mode

Object.hasOwnProperty does not check for inherited properties, only direct properties. We know that most things in JS inherits from Object which has its own methods, one of which is toString().
Dot/bracket notation also checks for inheirited properties.

toString in obj // true
obj.hasOwnProperty('toString') // false
obj.toString // function toString()
Enter fullscreen mode Exit fullscreen mode

Dot and bracket notation will coerce the value to truthy/valse value so if it is not set correctly it will return false.
Object.hasOwnProperty and in will still return true.

obj.value = 0;

// These blocks will not be executed as 0 is falsy
if (obj.value) { }
if (obj["value"]) { }
Enter fullscreen mode Exit fullscreen mode

< JS Advent 2 - Mutable and Immutable methods

Top comments (0)