Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

map[complement] === undefined vs !map[complement]

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading