JS Array Manipulation Quirks

Jen Chan - Dec 7 '19 - - Dev Community

In my previous post I mentioned I’d been practicing problem-solving by handwriting answers. It's taking much longer than on an IDE or cargo-programming, but bringing to light a lot of misunderstandings I had about JS methods:

1 The difference between slice() and splice()

.slice() extracts [0, n-1] array items as a new array.
.splice() mutates the original array by deleting items from [0, n] positions and returning it in place of the initial array. It also offers a third param to add items.

This is explained more thoroughly here and here from the functional programming perspective

2 One cannot simply iterate through a string

Applying .split('') by empty string or [...] (spread operator) returns an array of discrete letters

Exception: using charAt() in a for loop

Good points! You could iterate through a string directly though with a for loop, accessing the character at each index!

function forEachChar(str, cb) {
   for (let i = 0; i < str.length; i++) {
      cb(str.charAt(i))
   }
}
Enter fullscreen mode Exit fullscreen mode

3 The spread operator produces a shallow copy

If the array-to-copy is more than one level deep, thou shall not [...spread]. In a shallow copy, nested arrays (or objects) retain references to the original copy. Any changes of them affect initial and subsequent copy.

Shallow and deep copying in greater detail by Laurie Barth.

4 for (i of ...) vs for (i in ...)

The former enables iteration over arrays, strings, DOM node collections, maps, sets and generators. The latter iterates through object properties such as keys. for...of vs for...in

5 .join() vs. .push() vs .concat()

.push() mutates arrays and adds items to the end of the length
.concat() merges arrays, and runs faster than .join()

6 Some of my faves are problematic: they mutate arrays

i.e. shift(), unshift(), splice(), pop(), push()

It's now become my hobby to find alternatives that don't mutate the state, such as reduce() filter(), map(), some() and concat()

7 find() vs filter()

find() returns the first value that matches from a collection and stops unless I put it in a for loop.filter() returns an array of matched values.

8 forEach is a void function

It wasn’t clear when I read the MDN docs, and it seemed there were arguments both ways on blogs that it would mutate the original array. It doesn’t return anything, and with the help of the DEV community ❤️ I was able to discover that!

Related Reading


Are there any others you've come across that you'd like to add to this list? Let me know!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player