This is a memoization example from freecodecamp. The first 2 lines seem to achieve the same goal, determining the presence of an object key.
But using the first if-statement takes significantly longer to run, as if never even checks the memo object. How do these work differently?
const howSum = (targetSum, array, memo={}) => {
// if (memo[targetSum]) return memo([targetSum]); // why does this take longer?
if (targetSum in memo) return memo[targetSum]; // than this if-statement?
if (targetSum === 0) return [];
if (targetSum < 0) return null;
for (var num of array) {
var remainder = targetSum - num;
var remainderResult = howSum(remainder, array, memo);
if (remainderResult !== null) {
memo[targetSum] = [...remainderResult, num];
return [ ...remainderResult, num ];
}
}
memo[targetSum] = null;
return null;
}
console.log(howSum(7, [2, 3])); // [3, 2, 2]
console.log(howSum(300, [7, 14])); // null