Reputation: 1636
I am new to Java Script and found a type of function called 'Immediate Functions'. Why we use :
It is quite confusing that the for , while , if else statements do not create new variable scope but forEach loop do create a new scope. Is there any specific reason behind it? Here are the examples:-
var foo = 123;
if (true) {
var foo = 456;// updates the value of global 'foo'
}
console.log(foo); // 456;
let foo2 = 1111111;
var array = new Array(5).fill(5);
array.forEach(function () {
let foo2 = 222//creates new variable
// foo2 = 222//updates global variable
});
console.log('test' + foo2);
Upvotes: 0
Views: 325
Reputation: 5303
It's not the forEach
that creates the new scope, but the function
that is its argument. function
always creates its own this
.
Upvotes: 1