skip to Main Content

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


  1. 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 be true or false?

    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

    var arr = [0, 1, '', 'a', true, false, null, undefined];
    
    arr.forEach((val) => {
      console.log(`${val} is a ${typeof val}`);
      
      if (val) {
        console.log(' - truthy');
      }
    
      if (val !== undefined) {
         console.log(' - not undefined');
      }
    });
    Login or Signup to reply.
  2. 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

    const map = {};
    map['something'] = false;
    

    if (map[‘something’]) will not run (regardless if the key is there or not).

    Note map[‘something’] could have been false, NaN, ”, undefined, 0,
    all which would return false.

    (() => {
    
    // when using Map object.
    const map = new Map();
    map.set(4, true);
    
    // you get the value by using .get() not [].
    console.log(map.get(4));
    // true
    
    // when using object literal
    const map2 = {};
    // you can access the key using []
    map2[4] = true;
    console.log(map2[4]);
    // true
    console.log(map2[4] === true ? true : false);
    // true
    
    })();

    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)){ … }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search