cf.completefrontend

Write the codeMedium

Fix sum and sumRows so they return the right total and stop leaking globals.

sumRows([[1, 2], [3, 4]]) should return 10, but this version returns 3, and after it runs i and total exist as global variables. Find out why and fix both functions.

function sum(row) {
  total = 0;
  for (i = 0; i < row.length; i++) total += row[i];
  return total;
}
 
function sumRows(rows) {
  total = 0;
  for (i = 0; i < rows.length; i++) total += sum(rows[i]);
  return total;
}
Write this
function sum(row) {
  // your code
}
 
function sumRows(rows) {
  // your code
}
 
// sumRows([[1, 2], [3, 4]]); // 10
// typeof i;                  // "undefined"

The answer

Write it yourself first. Then compare it with a reference solution and the checks it passes.

Checking your sign-in…