1

I am starting to learn Javascript (coming from mainly Java) so that I can do web development. I was going through some learning resources and an example came up.

const sumArray = function(array) {
  let sum = 0;
  array.forEach(function(number) {
    sum += number;
  });
  return sum;
};

sumArray([2, 2, 2]);

Logically, this makes sense however, coming from java I am a little thrown off. sum is a variable that has block scope. However, the callback is manipulating the sum variable. Granted the callback is declared within the block in which sum is defined, it still throws me off because this isn't something that I would do in java (with my knowledge at least).

I am sure that I am missing something related to scope, functions, etc. but I would appreciate if someone could provide context to this and explain why this works.

jos
  • 11
  • 2
  • Scope in JavaScript nested functions works similar to scope in Java nested classes. Or lambdas. – Bergi May 13 '23 at 16:08

0 Answers0