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);
5
  • 1
    Possible duplicate of What is the scope of variables in JavaScript? Commented Feb 11, 2018 at 12:57
  • 1
    Read more about Execution context, scope, etc...: hackernoon.com/execution-context-in-javascript-319dd72e8e2c Commented Feb 11, 2018 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. Commented Feb 11, 2018 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. Commented Feb 11, 2018 at 13:13
  • @sébastien, thanks for pointing out. sorry for operating the terms poorly Commented Feb 11, 2018 at 13:17

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.