2

I was looking at the solution below to the "two sum" problem. They iterated through the array first and put all the numbers in an object. Then they did another for loop to see if the different was a key in the array but they checked for the key using hasOwnProperty. What is the difference of doing that vs. just checking for the key ex: if (obj[key]) { ....}

const twoSum_On_Better = (arr, target) => {
    let numObject = {};
    for (let i = 0; i < arr.length; i++) {
        let thisNum = arr[i];
        numObject[thisNum] = i;
    }
    for (var i = 0; i < arr.length; i++) {
        let diff = target - arr[i];
        if (numObject.hasOwnProperty(diff) && numObject[diff] !== i) {
            return [i, numObject[diff]];
        }
    }
}
MargieFowle3
  • 37
  • 1
  • 5
  • Check out Om Sao's answer here as well: https://stackoverflow.com/questions/9396569/what-is-property-in-hasownproperty-in-javascript – Ayudh Feb 22 '21 at 04:26

1 Answers1

2

Using obj[key] has two potential downsides:

  • It will check if the property is truthy, not only that the property exists

const obj = {
  prop: 0,
};
console.log(Boolean(obj.prop));
console.log(obj.hasOwnProperty('prop'));
  • It will perform the above check on the first object in the prototype chain that has the property. In contrast, hasOwnProperty will only check if the object itself, and not any of its internal prototypes, have the property.

const objProto = {
  prop: 'val',
};
const obj = Object.create(objProto);

console.log(Boolean(obj.prop));
console.log(obj.hasOwnProperty('prop'));

If, like in this case, you aren't dealing with prototypal inheritance, and the values on the object are sure to be truthy if they exist, feel free to use obj[key].

Some suggest to avoid dynamic property names in modern JS and to use Maps instead for purposes like these.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320