Daniyal Javaid
Daniyal Javaid

Reputation: 1636

forEach vs (for,while,if,else..) Variable scopes - JavaScript

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

Answers (1)

Matt Morgan
Matt Morgan

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

Related Questions