DEV Community

Bhupesh Chandra Joshi
Bhupesh Chandra Joshi

Posted on

Just Finished Array 101

What are arrays?

Array is an object ,as we know that everything is object in Javascipt. If your programming background is strongly typed language for ex- python ,java and c, you think of arrays as sequential chunks of memory that house collections of items of the same type,where each chunk of memory is of fixed size and has an associated index through which you can easily access it.

But as with many things in JavaScript, arrays come with a twist:

1-Iterating with for..in: Using for..in on arrays is dangerous because it iterates over array indices and any custom properties added to the prototype, which can cause issues if Array.prototype is extended.

Better way to iterate a array: Use the for of loop:

const colors = ['red', 'green', 'blue'];

for(const web of colors){
console.log(web);
}

Why for in loop not recommended for arrays.

2-Shallow Copying Issues: When cloning arrays, objects nested inside are still passed by reference. Modifying a nested object in the copy will mutate the original array.

3-Unexpected Mutation: Many methods modify the original array in place instead of returning a new one. For example, array.sort() changes the original array, whereas modern alternatives (like toSorted()) are pure.

4-Memory Inefficiency: Due to their fixed-size nature in underlying memory, very large arrays might require, in some contexts, manual memory management or cause inefficiencies during reallocation, especially if used as stacks.

5-Array-ish Objects: Some methods, like pop() or push(), can be used on array-like objects (e.g., arguments or DOM NodeList), unexpectedly adding a length property or modifying the structure of non-array objects.

We will deep dive them into later and follow for more such content.

Top comments (0)