0

So im brand new to learning javascript and although i have a basic idea of what var is, i would like to know why has var been used in the following code the second time when we are calling the function multiplyAll. I tested this function and the console shows the same answer when i dont use the var product and just call the multiply function with the nested array as arguments

function multiplyAll(arr) {
  var product = 1;

  for (i = 0; i < arr.length; i++) {
    for (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);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • In the global scope there's no difference. It's just a good habit to always declare variables. – Barmar Nov 16 '20 at 22:41
  • For `product`, it doesn't make much of a difference - it's just best practice. For `i` and `j` however, you definitely should declare those as local variables within the function. – Bergi Nov 16 '20 at 22:44
  • If you were to write this code today, the first `var product` would be `let product` (it has local scope and is mutable) and the second would likely be `const product` (assuming it doesn't need to be mutated). – jarmod Nov 16 '20 at 22:46

0 Answers0