I have this code and I really don’t understand why both of the console.logs show me false when there’s a 5 in the array
function diffArray(arr1, arr2) {
const newArr = [];
return 5 in arr2;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
console.log(5 in [1, 2, 3, 4, 5]);
I expected my function to return true
2
Answers
The
in
operator tells you if the value on the left is a property name of the object on the right.Since arrays are indexed from
0
, the array with 5 items in it has an item at positions 0, 1, 2, 3 and 4 but not 5. It also haslength
, and various other properties.You might be looking for the
includes
method which tells you if the argument you passed is a value in the array.The
in
operator resolves to a boolean reepresenting whether an object has a property with a given key. In your example, you have constructed an array with elements at index 0-4, but nothing at index 5, so5 in [1, 2, 3, 4, 5]
resolves tofalse
.If you want to check if an array contains a given value, you should use
includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) or [
indexOf` instead.For more complex checks, you can use
find
orfindIndex
instead. This is often needed when working with arrays of objects, which isn’t what you’re doing here.