Iteration Help Question

Does this function include iteration? It does not have a while or for loop. But has an "implicit Loop. Would this earn credit for having iteration on the create task?

function hadamardProduct(v1, v2) {

   if (v1.length != v2.length) {

         throw new Error(

               "Arguments to `hadamardProduct` must be of the same length."

        );

  }

 // Implicitly loops through the array

return v1.map(function(v, i){return v * v2[i];});

}

Hey there! Welcome to the forums.

This code definitely does contain a loop, which is the .map call. With .map, you have a function that is called for each item of an array (in order). Using .map on an array is, at its core, the same thing as iterating through an array with a for loop.

If you need any more explanation, feel free to ask!

I think the important part here is that the student is able to explain how the code leverages iteration. If there is a visible for/while loop, that is easier to articulate for most students than describing how a map function does in fact use iteration. That said, the “behind the scenes” loop of map should be viable for any student that can articulate the abstraction.

1 Like