Take each value and divide it by 100,
Indeed, it is important to divide each value by 100 and then store the resulting value back into the array. In JavaScript, when you want to perform a calculation and save the result, you should use the following syntax:
left-hand-side = calculation
This means using the assignment operator (=
) to assign the outcome of the calculation to a variable, an element in an array, or a property.
In this specific scenario, the "calculation" involves dividing the value of the array element by 100. Therefore, the expression would be written as:
example[i] / 100
You might question why example[i/100]
does not work. Reflect on it. The content surrounded by the square brackets []
acts as an index within the array. You do not intend to divide the index i
by 100; rather, you aim to divide the value at index i
by 100.
The objective is to place the outcome--the division of the element at index i
by 100--back into the array at that same position. Hence, the "left-hand-side" is also element[i]
. Consequently, the full statement becomes
example[i] = example[i] / 100;
Your initial attempt, which was
( example [ i/ 100] )
does not align with the desired outcome for several reasons. Firstly, you are dividing the index by 100 rather than the value located at that index. Secondly, you are failing to assign the result to anything--leading to its immediate disposal.
Simply modifying the previously questionable line to example[i] = example[i] / 100;
will yield a functional code. Extraneous constructs like forEach
, map
, or arrow functions are unnecessary (though understanding and applying them eventually is beneficial).
In situations where you are assigning the outcome of dividing a specific array element back to that same array element, JavaScript offers dedicated assignment operators which can streamline your code. Here, the "division assignment operator" comes into play, established as:
example[i] /= 100;
^^
However, choosing to use this operator purely depends on brevity preference.