DEV Community

Cover image for Function Scope in JS
Mohd Ahshan Danish
Mohd Ahshan Danish

Posted on

Function Scope in JS

Functions in Javascript run in the scope they are defined, not in the scope they are executed.

var baz;
(function() {
  baz = function() {
    return foo * bar;
  };
  var foo = 20;
  var bar = 2;
})();

console.error(baz());

//output: 40
Enter fullscreen mode Exit fullscreen mode

I will be posting tricks I have been using in my journey.

So follow me on LinkedIn.

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Not 100% true. If you create a function using the new Function(...) syntax (which is rare and unusual) - they are actually attached to the global scope, and not the scope in which they were defined.