I have a hashmap, and i’m doing a check to see if a key is not undefined. However, my code only works when I specify that. For instance:
if (map[key] !== undefined) {
/* code will run */
}
This code works as expected. However, I wanted to shorten the code to just:
if (map[key]) {
/* code will not run */
}
Shouldn’t these two be the same thing? The code will still run but I only get the expected output for the first code snippet.
2
Answers
When you check
if (map[key])
that is saying "does this value appear to be falsey". Any value can be passed to an if statement, so what happens when you pass a string'foo'
– will it betrue
orfalse
?Lots of other value types can evaluate to a boolean-like value, which is why you want to check for the specific value with
map[key] !== undefined
in some cases, and in others you might not. It just depends.Run this demo to see how the different value types are treated here
I’m not sure what you mean by "will not run". If the key you’re accessing has a boolean value of false it will NOT run.
ie
if (map[‘something’]) will not run (regardless if the key is there or not).
A more accurate way to determining if a key exists is to use hasOwnProperty. Do NOT use
in
as it includes prototype properties as well.Example:
if (map.hasOwnProperty(THE_SEARCHED_FOR_KEY)){ … }