0

I found an answer for the Two Sum question on leetcode; the solution used || between obj[delta] || obj[delta]. Does anyone know why they used it in this way and what does it mean?

for(let i = 0; i< nums.length; i++) {
    let cur = nums[i];
    
    let delta = target - cur;
    if(obj[delta] || obj[delta] === 0) {
        return [obj[delta], i];
    }
    
    obj[cur] = i;
}
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Wolfsbane
  • 13
  • 3
  • 1
    `||` is the [Logical OR](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR) operator. And in this case, it's between `obj[delta]` and `obj[delta] === 0`. That's typically a check for a number that exists (You have to separate the check for `0`, because `0` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) in JavaScript. – M0nst3R May 17 '22 at 15:59

1 Answers1

0

0 is falsy in javascript, so they're making allowance for the obj[delta] value to be 0. In this two-sum task they seem to be allowing [0, target] as a valid answer.

Another interesting OR fact: the || operator actually returns the value of the first non-falsy operand. So it can also be used to return default values.

Nicolas Goosen
  • 583
  • 5
  • 14