I am new to Java Script and found a type of function called 'Immediate Functions'. Why we use :
- perform tasks as soon as function is defined
- creating a new variable scope
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);