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]];
}
}
}