I need something of a HashMap in javascript. Can we do this:
var map = {};
map['foo'] = true;
map['zoo'] = true;
...
if (map['foo']) {
// yes, foo exists.
}
else {
// no, foo does not exist.
}
how do we properly check for the existence of the property without inserting it if it does not exist? For example, I don’t want map.foo to exist after the above check if I didn’t explicitly add it,
Thanks
In your example, checking for:
Not only checks if the property is not defined on the object, the condition expression of the
ifstatement will evaluate tofalsealso if the property holds a value that coerces tofalseon boolean context (aka falsy values), such as0,NaN, an empty string,null,undefinedand of coursefalse, e.g.:To check if a property exist on an object, regardless its value -which can be falsy, even
undefined– , you can use thehasOwnPropertymethod, for example:The only problem with this method is that if someone adds a property named
hasOwnPropertyto an object, it wont work, for example:If you execute
obj.hasOwnProperty('prop'), it will give you aTypeError, because the object contains a string property that shadows the method -invoking the string would cause the error-.A workaround to this is to call the
hasOwnPropertymethod directly from theObject.prototypeobject, for example:You can also use the
inoperator:The difference with the first method is that the
inoperator checks also for inherited properties, for example:See also:
Edit:
Extending my response to the @slebetman comment, about checking
if (map.foo !== undefined).As I was commenting, there are some concerns about accessing the
undefinedglobal property and also a semantic difference between checking a property value vs. property existence.The
undefinedglobal property is not defined as read-only ECMAScript 3rd Edition Standard, (is nowwritable = falseon ES5 🙂In almost all implementations its value can be replaced.
If someone makes:
Also the semantic difference: by testing if
map.foo !== undefinedwe are not technically only checking if the property exist on the object or not, a property can exist, holding undefined as a value, for example: