I am having trouble understanding how this code works, especially after the if(y in hash)
statement. I don't see any values being pushed into hash
initially. Can someone explain what happens behind the scenes and the significance of y in hash
?
var twoSum = function(nums, target) {
const hash = {}
for (const i in nums) {
const x = nums[i];
const y = target - x
if (y in hash)
return [i, hash[y]]
hash[x] = i
}
}
let arr = [2, 3, 4, 5, 6]
console.log(twoSum(arr, 11))