Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

array.includes doesn't work when checking if an iterator exists in array

I’m encountering some unexpected behavior in my JavaScript code which I’d like to understand. I want a one-line function to detect if a number exists inside an array of integers, the number being checked is the iterator of a loop in another array. I’m using the standard includes() function, should note the same happens with an indexOf() >= 0 check. For this test we have the following code:

const array1 = [0, 1, 2, 3];
const array2 = [1, 2];
for(let i in array1)
    console.log(array2.includes(i));

To my surprise each output returns false instead of the expected false true true false sequence. How can this be? I know I’m checking i not arr[i], but i still corresponds to the numbers included in those arrays: 0 is still 0, 1 is still 1, etc. Using arr.includes(1) does return true, so why not arr.includes(i) when i is also 1?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

for...in loops through all properties, not values. Arrays are objects, and their properties are 0 ... array.length, so i inside the for loop is 1, 2, 3 and 4.

You should be using a for...of loop instead:

const array1 = [0, 1, 2, 3];
const array2 = [1, 2];
for(let i of array1)
    console.log(array2.includes(i));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading