Includes vs. In

Today I ran into some trouble with a line of code that seems to be misleading. I tried to use

if (!(arr[n][i] in arr[0])){

but I found I had to rewrite the code as

if (!(result.includes(arr[n][i]))){ 

I am having difficulty understanding the difference between the array.includes() function and the if…in syntax. It seems that the if…in syntax is transferable between arrays and objects as it seemed to be syntactical as

for (let property in source)

Is the if…in syntax actually a dependable/usable syntax for something and how does it differ from array.includes()?

Also, although the if…in seemed to be syntactical, there was an instance where it seemed not to work with a single element array where an object if ({x}in [{x}]) seemed to evaluate to false.

When in doubt check the documentation

The in operator returns true if the specified property is in the specified object or its prototype chain.

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

To iterate over an array its correct to use the for...of statement rather than the for...in (not recommended for array iteration). The other one is the traditional for-loop statement, for(let i = 0; i < array.length; i++) { ... }.

includes method is for checking if an element exists in the array or not. Another way to achieve the same functionality is to iterate over the array:

function elementExists(arr, ele) {
    for (let e of arr) {
        if (e === ele) return true;
    }
    // return false;
}

Why does the in operator seem to evaluate in the for (element in array) syntax? What is it doing in this situation? If you are pointing to an object in an array is it evaluating the next object?

I don’t see documentation for an of operator. Does the (let element of array) work in a multidimensional array? It looks like it uses a dummy variable syntax where if you are looking for ele in an array you can search for it as e. In fact this seems to be an elaborate check that could never be superior to includes unless you want to use == instead of ===. When would you do this rather than array.includes()?

Refer this: for…of @MDN.

You can use the for-loop statements (both for…of and the traditional for_loop, and together) to work with multi-dimensional arrays.

The elementExists function I had mentioned is for explaining the concept of includes functionality.

that’s the for…in loop, that’s a different thing altogether

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.