loading...

re: Mastering Hard Parts of JavaScript: Callbacks I VIEW POST

FULL DISCUSSION
 

Being that this is intended to teach "the hard parts of JavaScript" I think you should take some care to not teach bad habits inadvertently as well.

Specifically exercise 6. You're reusing initialValue as your accumulator. Firstly, unless you're doing some kind of crazy micro-optimization, just don't ever reuse function inputs in your functions. Ever. You will undoubtedly create unintended side effects that waste countless hours debugging.

Consider the case where the array is not an array of primitives. You assign the initialValue to array[0] if an initialValue wasn't defined. Seems innocent enough. In this case though, it's a reference and not a copy. Now on each iteration of the forEach you're modifying the first element in the input array! Surely that's not what's intended and, especially for your target audience here, you're going to create a very frustrating future experience for them.

Now also consider the case where initial value is defined but is not a primitive value. If I was inputting something I wanted to use later in my code it would be unexpectedly changed!

Instead you should take care to create a copy of array[0] and initialValue when setting the value for your accumulator.

 

You're 100% correct there. I should have assigned initialValue to a new variable to make sure the function has no side effects. Bad miss on my part. Thanks for pointing out 😊

 

maybe then update the post as not everyone is going to fully read the comments section :)

Code of Conduct Report abuse