loading...

re: Find and Replace elements in Array with JavaScript VIEW POST

FULL DISCUSSION
 

Hey man -- the first section with regards to removing items from an array appears to be incorrect as Array.prototype.pop() and Array.prototype.shift() do opposite of what you say. The comment showing the results also appear to be incorrect. I believe the they should be:

Your current code:

const arr = [1,2,3,4,5];
arr.pop();
arr;
// [1,2,3,4]

const arr2 = [1,2,3,4,5];
arr2.shift();
arr2;
// [1,2,3,4];

Corrected code:

const arr = [1,2,3,4,5];
arr.pop(); // 5
arr; // [1,2,3,4]

const arr2 = [1,2,3,4,5];
arr2.shift(); // 1
arr2; // [2,3,4,5]

I think it's also worth noting, when introducing these topics, that there are Array methods that are mutable and others that are not (return new data structures). A lot of the ones that you've mentioned here mutate the original array. There are some tricky situations that people run into if they aren't aware of these behaviors. I know that you somewhat note that when presenting Array.prototype.filter, but it would be useful to show that the original array is left unchanged. I mention this because modern JavaScript adopts a lot of functional programming constructs, like immutable data types, that reduce bugs in code (e.g. React, Redux with ImmutableJS). To return a new data structure each time, I typically end up using Array.prototype.reduce. This is one of my most used functions or methods in various programming languages.

Otherwise, nice write-up! :)

 

Awesome find, thanks for catching that error. Also thanks for the feedback, I'll try to expand on the explanation of each method :)

Code of Conduct Report abuse