Quick question on this exercice. I have found and understood the solution.
But I am wondering on another point.
What if the variable product is already existing outside the function.
I have tried to declare the variable product first. Then I have tried to call the function with this variable. Please see the code below.
This is wrong but I don’t know why.
Thank you for your help.
Your code so far
var product = 1;
function multiplyAll(arr, product){
for (var i=0; i < arr.length; i++){
for (var j=0; j < arr[i].length; j++){
product = arr[i][j] * product;
}
}
return product;
}
multiplyAll([[1,2],[3,4],[5,6,7]], product);
}
function multiplyAll(arr) {
var product = 1;
// Only change code below this line
function multiplyAll(myArr){
for (var i=0; i < myArr.length; i++){
for (var j=0; j < myArr[i].length; j++){
product = myArr[i][j] * product;
}
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0.
The problem is you created a function named multiplyAll inside a function with the same name. I’m not sure why you did that, because creating a new function inside isn’t necessary. The reason it didn’t work was because the function inside never ran, you didn’t call it, so it would return 1 everytime. Basically, this is what it should look like:
// Only change code below this line
for (var i=0; i < arr.length; i++){
for (var j=0; j < arr[i].length; j++){
product = arr[i][j] * product;
}
}
// Only change code above this line
Actually, my code is the one above. I think the tool insterted my code below the requested code by the exercise.
When I tried I just add the code above and launched the test.
There were only one function. But for sure the way I used product is wrong but not sure why.
You still have a function call inside something else, or a stray curly bracket at the end
The issue if you use a global variable is that each function call will change the global variable, as such you may find unwanted results there when you have various function calls. It is recommended that a function doesn’t change global variables directly for that reason