While taking JS211 @AustinCodingAcademy we covered how different items are either mutable or immutable, and I thought I understand. My understand was that different methods or functions could mutate your original value, which is true. This week while using arrays for a MasterMind game I was to develop, I ran across more of the meaning.
I had wrote code similar to shown below. My thought was I did not want to change (or mutate) “myArray” during this part of the code (I did need it to change in other parts of the code) so I made a copy for myArray2. I compared myArray2 to a solution and if any items matched I was going to “null” out that space in myArray2. The code worked as I expected it to. See below.
But to my surprise it also mutated “myArray. See code below.
I solved my problem by use Array.from(). See code below. I am sure there are tons of other ways to solve this. Knowing what I know now I probably would have approached this different, but this one bug was causing my game to have issues and this seemed to be a clean way to solve it.
We also started covering more higher level functions. Two that we covered are forEach() and map(). They are similar but the forEach() method doesn’t actually return anything (undefined). It simply calls a provided function on each element in your array. This callback is allowed to mutate the calling array. … The difference is that map() utilizes return values and actually returns a new Array of the same size.
As mentioned we are covering higher order functions. A higher order function is a function that takes a function as an argument, or returns a function. Higher order function is in contrast to first order functions, which don’t take a function as an argument or return a function as output.