I mean, includes
is an Array prototype but in
can be used with arrays too, so what is the main difference between both?
includes() The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
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.
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.
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.
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
"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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With