Within my code, there is a forEach loop containing a nested for loop. It's interesting that, even though I have a statement word = foo
outside of the for loop but still inside the forEach loop, I can actually log the value of word
after the entire forEach loop. On the other hand, if I change it to let word = "foo"
, the console log statement fails with an error message saying that word
is not defined. Why does this happen?
function mainFunction() {
array.forEach(function (element, index) {
for (var key in list) {
//do something
}
word = "foo"
}
console.log(word)
}