Manuel del Pino Lucena
Manuel del Pino Lucena

Reputation: 203

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

I mean, includes is an Array prototype but in can be used with arrays too, so what is the main difference between both?

Upvotes: 20

Views: 8849

Answers (4)

Abhijit
Abhijit

Reputation: 252

"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

Upvotes: 5

T.J. Crowder
T.J. Crowder

Reputation: 1074266

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.

Upvotes: 5

Maksims Kitajevs
Maksims Kitajevs

Reputation: 225

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

Upvotes: 3

Ori Drori
Ori Drori

Reputation: 191976

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

Upvotes: 29

Related Questions