0

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);
Daniyal Javaid
  • 1,426
  • 2
  • 18
  • 32
  • 1
    Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Ayush Gupta Feb 11 '18 at 12:57
  • 1
    Read more about Execution context, scope, etc...: https://hackernoon.com/execution-context-in-javascript-319dd72e8e2c – Arber Sylejmani Feb 11 '18 at 12:57
  • 1
    Using `let` would create a new scope inside `if` block as well. `let` defines a new scope in any block. So does `const`. `var` scope on the other hand is restricted by the surrounding function clause. – oniondomes Feb 11 '18 at 12:58
  • 2
    @oniondomes to be clear, using the `let` keyword does not create a new scope, using the `let` keyword only means that the variable created will have block scope only and not function scope as would be the case with the `var` keyword. There is no new scope because `this` does not change, it is still the `this` of the current function scope. – Sébastien Feb 11 '18 at 13:13
  • @sébastien, thanks for pointing out. sorry for operating the terms poorly – oniondomes Feb 11 '18 at 13:17

1 Answers1

1

It's not the forEach that creates the new scope, but the function that is its argument. function always creates its own this.

Matt Morgan
  • 4,900
  • 4
  • 21
  • 30