Why a function in this challenge?

Hello, I understand how to solve this issue but I have a hard time understanding why they want us to use a function if we never even invoke it or console.log it? Wouldn’t it be easier and time-saving to simply solve this challenge using the code below?

var arr = ([[1,2],[3,4],[5,6,7]]);
var product = 1

for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
product *= arr[i][j];
}
}

  **Your code so far**

function multiplyAll(arr) {
var product = 1;

for (var i=0; i < arr.length; i++) {
  for (var j=0; j < arr[i].length; j++) {
    product *= arr[i][j];
  }
}

return product;
}

var product = multiplyAll([[1,2],[3,4],[5,6,7]]);

console.log(product);

  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36

Challenge: Nesting For Loops

Link to the challenge:

Well, I can think of two big reasons:

  1. It’s a good habit to get into, wrapping things in functions. It allows you to separate, organize, and reuse code.
  2. It makes it easy to test. The FCC program can grab that function, feed it certain inputs, and check if it gives the expected result. What you have would only check one set of input data. Good unit testing often uses a few or many data to test, making sure strange, “edge cases” are tested.

Would it be “easier and time-saving” without a function?

Maybe from your perspective, it would be a few fewer lines to type. But in terms of good coding practices, I think this is a reasonable thing to do.

1 Like