0

Something that recently broke my code is that I naively thought that:

'+' in ['+','-',...] = true.

The only problem is that it actually evaluates to false!

Someone please help me understand what is going on here!

Nathan
  • 1
  • `=` is for assigning values to variables or properties; `==` and `===` are for comparison. Also the `in` operator binds loosely; it's a good idea to parenthesize. – Pointy Sep 17 '19 at 15:32
  • 1
    [`in` is an operator not a function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in) – Taki Sep 17 '19 at 15:32
  • 1
    You need `Array#includes` to check whether an item is present in an array. – Tushar Sep 17 '19 at 15:33
  • Also of course "+" is not a property of the array; it's the value of an *element* of the array but that's not what `in` does. – Pointy Sep 17 '19 at 15:33
  • 1
    @Pointy IIRC, the `in` operator in other languages (Python?) actually checks if a value is in an array. So, if coming from there, it seems like a normal assumption to make that the JS `in` works the same way. – VLAZ Sep 17 '19 at 15:34
  • The [`in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in) operator checks if an object has that property which is not the case. For that you should use [`includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) method. Funny thing in JS, arrays are objects where each element is stored in a numeric property matching that element position, so `0 in ['+'] == true` and `1 in ['+'] == false`. – Anler Sep 17 '19 at 15:38
  • @VLAZ yes I'm sure you're right; knowing language A while learning language B can cause all sorts of problems – Pointy Sep 17 '19 at 15:48

1 Answers1

2

The in operator returns true if the specified property is in the specified object or its prototype chain.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

demkovych
  • 7,827
  • 3
  • 19
  • 25