skip to Main Content

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


  1. 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 has length, and various other properties.

    const arr = [1, 2, 3, 4, 5];
    
    console.log(arr[5], 5 in arr);
    console.log(arr[4], 4 in arr);
    console.log(arr.length, 'length' in arr);

    You might be looking for the includes method which tells you if the argument you passed is a value in the array.

    const arr = [1, 2, 3, 4, 5];
    
    console.log(arr[4], arr.includes(5));
    console.log(arr[3], arr.includes(4));
    console.log(null, arr.includes('length'));
    Login or Signup to reply.
  2. 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, so 5 in [1, 2, 3, 4, 5] resolves to false.

    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.

    const arr = [1, 2, 3, 4, 5];
    
    console.log(arr.includes(5)); // <- true
    console.log(arr.includes(6)); // <- false
    
    console.log(arr.indexOf(5)); // <- 4
    console.log(arr.indexOf(6)); // <- -1, which means it's not there
    

    For more complex checks, you can use find or findIndex instead. This is often needed when working with arrays of objects, which isn’t what you’re doing here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search