What's the equivalent of "has_key" in javascript?
hasOwnProperty
:
if(Object.prototype.hasOwnProperty.call(dictionary, key)) {
// ...
You can also use the in
operator, but sometimes it gives undesirable results:
console.log('watch' in dictionary); // always true
Either with the in
operator:
if('school' in dictionary) { …
Or probably supported in more browsers: hasOwnProperty
if({}.hasOwnProperty.call(dictionary, 'school')) { …
Could be problematic in border cases: typeof
if(typeof(dictionary.school) !== 'undefined') { …
One must not use != undefined
as undefined is not a keyword:
if(dictionary.school != undefined) { …
But you can use != null
instead, which is true for null
, undefined
and absent values:
if(dictionary.school != null) { …
The 'in' operator.
if ('school' in dictionary)