1

I use

1 in [1]; // ===> true

But

const node = document.body.querySelector("div"); 
node in [node]; //===> false

Can anyone help me understand?

Y.Jie
  • 148
  • 1
  • 8

1 Answers1

3
1 in [1]; // ===> true

No, that evaluates as false. Here is a demo:

console.log(1 in [1]);

The in operator will evaluate as true if the left-hand side converted to a string exists as a property name on the right hand side. Your array has a property '0' with a value of 1 (and also some other properties like length and indexOf which are inherited from the Array prototype).

The in operator doesn't check if the value on the left exists as a value in the array on the right. You need the includes method for that.

console.log([1].includes(1));
const node = document.body.querySelector("div"); 
console.log([node].includes(node));
<div>...</div>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335