Javascript Gotcha — forEach loop

DSL
1 min readOct 3, 2021

--

When using forEach to iterate through an array of int and define a variable “total”, and then expect to sum up every element in the array in some ways to “total”. For example, the following code is doing exactly what I described above.

function minimumWaitingTime(queries) {queries = queries.sort((a, b) => a - b);  let total  queries.forEach((query, index) => {    total += query * (queries.length - (index + 1));  });  return total;}const array = [3, 2, 1, 2, 6];minimumWaitingTime(array);

however, it does not work and total inside each loop is logged as NaN. The solution to make it work is to initialize “total” as 0.

function minimumWaitingTime(queries) {queries = queries.sort((a, b) => a - b);let total = 0queries.forEach((query, index) => {total += query * (queries.length - (index + 1));});return total;}const array = [3, 2, 1, 2, 6];minimumWaitingTime(array);

Now, it works as expected.

--

--

DSL
DSL

Written by DSL

Sr software engineer. Love in Go, JavaScript, Python, and serverless AWS. Follow me for tech insights and experiences. follow me on twitter @terraformia