Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 971
Manuel del Pino Lucena Avatar asked Jan 29 '18 10:01

Manuel del Pino Lucena


People also ask

What is the function of the includes () in arrays?

includes() The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

Can you use in operator on array JavaScript?

JavaScript in operator to check whether the Array is using a key or the index for its values. JavaScript's “in” operator can also work with arrays as well.

How does the in operator work in JavaScript?

What exactly is the JavaScript in operator? The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists.

Can you use the IN operator in an array?

just like the js for in loop which iterates the object properties, the in operator checks if the specified property is in the specified object or its prototype chain. it does not check whether an element is in an array.


2 Answers

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
like image 97
Ori Drori Avatar answered Oct 18 '22 15:10

Ori Drori


"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
like image 37
Abhijit Avatar answered Oct 18 '22 16:10

Abhijit