Home > Enterprise >  How this javaScript code is work? after if condition
How this javaScript code is work? after if condition

Time:04-10

i do not understood, how this code working after if(y in hash) most complicated for me is hash is empty and i do not push any value in hash so what will happened behind the scene and y in hash what its meaning?

var twoSum = function(nums, target) {

  const hash = {}
  // console.log(hash)
  
  for (const i in nums) {
    const x = nums[i];
    const y = target - x
    // console.log(y)
    if (y in hash)
      return [i, hash[y]]
    hash[x] = i
  }

}

let arr = [2, 3, 4, 5, 6]
console.log(twoSum(arr, 11))

CodePudding user response:

hash is empty and I do not push any value

hash[x] = i part add values to hash, because it is out of if(y in hash) condition

y in hash what it's meaning?

As Nick Parsons mentioned in a comment "it's checking if the key stored in y is a key in the hash object (or its prototype chain)"

  • Related