Check if an object has a property

JS
S
JavaScript

Two simplest ways of checking if an object has a property, hasOwnProperty and via in.

1// Better version
2if (Object.prototype.hasOwnProperty.call(data, 'doing')) {
3    // update working time slots
4}
5if (Object.prototype.hasOwnProperty.call(data, 'completed')) {
6    // update working time slots
7}
8
9// the native 'hasOwnProperty' method
10var hasOwn = function(tag, atr) { return document.createElement(tag).hasOwnProperty(atr); }
11
12// the 'in' operator
13var in = function(tag, atr) { return atr in document.createElement(tag); }
14
15hasOwn('audio', 'preload');  // returns true
16in('audio', 'preload'); // returns true

Created on 2/17/2018