DEV Community

Discussion on: Mastering Hard Parts of JavaScript: Callbacks I

Collapse
 
jmatty1983 profile image
Jason Matthews • Edited

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.

Collapse
 
internettradie profile image
Ryan Ameri

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 😊

Collapse
 
shanwshaw profile image
shawnshaw • Edited

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

Thread Thread
 
internettradie profile image
Ryan Ameri

Done!

Collapse
 
jkoo92 profile image
JKoo92

Hey Ryan thank you for this post that I just came across. Do you have your previous solution by any chance so that I can better understand what Jason is pointing out in the comment? Is he saying that in your previous solution you just set " let accum = initialValue" ?