Confused about scope

let array = [1,2,3,4,5,6]
const count = function(a) {
  let x = 0
  a.forEach(function(item) {
    x += item
  })
  return ` ${x}`
}
document.write(count(array))

In the above code, why is it not necessary to return the value of x from inside forEach method ( something like return x += item)?

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

1 Like

x is declared outside of the forEach and exists throughout the count function.

1 Like

Pardon me if it’s something obvious that I’m missing but why doesn’t the following work?

let x = 1
const f = function () {
 // return x += 1
  const g = function () {
    return x = x+1
  }
  return x
}
f()
document.write(x)

Value of x doesn’t change when I try to change it in a function inside another function

You can’t have an assignment operator in a return statement. (I mean, obvioiusly you can, but it won’t do what you want.)

Also - You never called your g function in the above code, so it won’t run.

Hi @newbiewebdeveloper,

In addition to @ArielLeslie response, forEach expects the function declared as its first parameter to perform some sort of side effect and doesn’t expect it to return a value. It basically says, here’s the value at this point of the array, do what you want with it. Returning a value would essentially just be lost as forEach does nothing with it. See here.

You could rewrite that logic to use reduce, which would kind of do what I think you’re expecting. See here for more details on it.

// Using some ES6 stuff for better readability.
const array = [1,2,3,4,5,6]

const count = (a) =>
  a.reduce((prev, curr) => prev + curr, 0)

document.write(` ${count(array)}`)
1 Like