I'm new to coding so apologies (and please correct me) if I use wrong terminology. I was doing the following coding challenge: Given an array with multiple values, write a function that returns a new array that only contains the maximum, minimum, and average values of the original array.
This is the code I came up with during my first attempt: First attempt
Eventually I figured out through trial and error that the problem was the location of my arrnew variable. I also fixed the average Expression and the correct algorithm is: Correct algorithm
I assumed that since the max, min, and avg were changing (is there a better term for this?), the var arrnew would pick up these new values but obviously that wasn't the case. I guess my question is when does line order matter? Or probably more specifically, are there any simple rules or principles I should be aware of to help me better understand command line coding (I dont know if this is called command line coding).
Thanks
It is because of the compiler, the compiler will always go from top to bottom, so always try to structure your code in an ordered way.
When you do this:
This places a copy of the contents of
max
,min
,avg
into the array. Future changes to whatmax
,min
andavg
contain will not affect the array in any way.So, if you do;
Note, the contents of
arrnew
are not affected at all by subsequent changes to whatmax
,min
oravg
contain. This is just how Javascript (and most languages work).