What are the pros and cons of function-level scope specifically in Javascript compared to block-level scope in languages like Java?
I would like to see examples of function-level scope usage that would be harder or impossible to implement using block-level scope.
JavaScript has function scope: Each function creates a new scope. Variables defined inside a function are not accessible (visible) from outside the function. Variables declared with var , let and const are quite similar when declared inside a function. They all have Function Scope: function myFunction() {
Function Scope: When a variable is declared inside a function, it is only accessible within that function and cannot be used outside that function. Block Scope: A variable when declared inside the if or switch conditions or inside for or while loops, are accessible within that particular condition or loop.
The scope determines the accessibility of variables and other resources in the code, like functions and objects. JavaScript function scopes can have two different types, the locale and the global scope. Local variables are declared within a function and can only be accessed within the function.
There are three types of scope in JavaScript — 1) Global Scope, 2) Function Scope, and, 3) Block Scope.
The first example that comes to mind is: JavaScript's handling of closures would be much more expensive if implemented with block-level scope.
When you enter a function in JavaScript, an object is allocated (well, a couple, but we'll focus on one) that ends up being the "variable object" — that is, where all the arguments and local vars for that function call are held (as properties). It's this object that the closure actually uses (not just the "symbols" it appears to use; that's a common misconception). These objects are strung together in a chain, called the scope chain, which is used for resolving unqualified symbols.
Imagine how much more expensive that would be if every block introduced new scope.
I would like to see examples of function-level scope usage that would be harder or impossible to implement using block-level scope.
Maybe it will sound obvious, but you can implement recursion in function-level scope, which can be often useful, for example:
var x = 5; // global scope
(function (y) { // y - locally scoped variable on each execution
y && arguments.callee(--y); // recursion!
console.log(y);
})(x);
That is mostly impossible to implement with block-level scope.
In the above example the function will initially be executed passing the value of the outer x
variable to it, before the function is invoked a new execution context is setup, that initializes a new lexical scope, where the y
formal parameter is bound to it.
After that, the function expression is executed again -if y
is not 0
- initializing on each execution a completely new lexical scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With