What is the difference between "in operator" and "includes()" for JavaScript arrays

Array.includes() checks for the existence of a value in an array, while the in operator checks for the existence of a key in an object (or index in the case of arrays).

Example:

var arr = [5];

console.log('Is 5 is an item in the array: ', arr.includes(5)); // true
console.log('do we have the key 5: ', 5 in arr); // false
console.log('we have the key 0: ', 0 in arr); // true

Array#includes determines whether a given value is an entry in the array. in checks to see if the given string is a known property of the object (or any of its prototypes). They are very different things.

..."in" can be used with arrays too...

It can, to check whether a property with a given name exists, but that's very different from what includes does:

var a = [10];
console.log(a.includes(10)); // true, 10 is an entry in
console.log(10 in a);        // false, there's no property called "10" in the array
console.log(0 in a);         // true, there IS a property called "0" in the array

Using in on an array is a relatively unusual operation, mostly reserved for use on sparse arrays.


With in operator you can check if key exists, with includes() you can check if value exists


"includes" checks whether a value exists in an array where as "in" operator checks whether a key/index exists in obj/array.

var arr = [15, 27, 39, 40, 567],
  obj = {
    num1: 3,
    num2: 34,
    num3: 89
  };;
console.log(arr.includes(27)); // returns true checks 27 as a value in the array
console.log(2 in arr);         // returns true checks 2 as index in the array
console.log("num1" in obj);    // returns true checks num1 as key in obj