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);
letwould create a new scope insideifblock as well.letdefines a new scope in any block. So doesconst.varscope on the other hand is restricted by the surrounding function clause.letkeyword does not create a new scope, using theletkeyword only means that the variable created will have block scope only and not function scope as would be the case with thevarkeyword. There is no new scope becausethisdoes not change, it is still thethisof the current function scope.