0

Sure this is simple as but I can't find any documentation atm. I've been digging into ES6 and found the use of logic in expressions. As an example:

let arr = [1,2,3,4]
let result1 = (arr[2] || 0) //returns 3
let result2 = (arr[5] || 0) //returns 0

I understand whats going on (and like the idea!) but don't get why the result is an integer and not a boolean as I'd expect when using logic?

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
Chris Barrett
  • 571
  • 4
  • 23
  • 1
    Do you know what `||` is and how it works? Why do you expect it to be a boolean? You might find your answer here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators – evolutionxbox Jun 22 '20 at 15:44
  • I understand it as `OR`? – Chris Barrett Jun 22 '20 at 15:45
  • Specifically the comment that says: "it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true, or false value". – zero298 Jun 22 '20 at 15:48
  • think it does, yes. thanks – Chris Barrett Jun 22 '20 at 15:48
  • It is the logical-or operator. I think you have made some assumptions about how it works. The mdn article I linked does a good job of explaining it. – evolutionxbox Jun 22 '20 at 15:48
  • it reads like `result1 = 3 or 0` and only returning `0` when it cant computer `arr[2]` – Red Baron Jun 22 '20 at 15:49
  • Also relevant: [What does the construct x = x || y mean?](https://stackoverflow.com/q/2802055) | [What does “var FOO = FOO || {}” (assign a variable or an empty object to that variable) mean in Javascript?](https://stackoverflow.com/q/6439579) | [Javascript AND operator within assignment](https://stackoverflow.com/q/3163407) – VLAZ Jun 22 '20 at 15:50

0 Answers0