I am solving the following leetcode question and have the solution below
const twoSum = (numbers, target) => {
let map = {}
let result = []
for (let i = 0; i < numbers.length; i ) {
let complement = target - numbers[i]
if (map[complement] === undefined) {
map[numbers[i]] = i
} else {
result[0] = map[complement] 1
result[1] = i 1
}
}
return result
};
If I replace map[complement] === undefined
with !map[complement]
I return an empty array. In my mind both should return true
. Why does the latter breaks my code?
CodePudding user response:
map[complement] === undefined
only becomes true
when there is no element with the key equal to complement
while !map[complement]
becomes true
in all the cases where its result is a falsy value.
Falsy values include but are not limited to, ""
, false
, undefined
, null
, 0
, -0
, etc.
In other words, the first case is a sub set of the second.