Pros and cons of the functional level area (especially in Javascript)

What are the advantages and disadvantages of the functional level area, especially in Javascript, compared to the block level area in languages โ€‹โ€‹like Java?

I would like to see examples of using a functional level area that would be more difficult or impossible to implement using a block level area.

+6
javascript
source share
3 answers

The first example that comes to mind is this: handling JavaScript closures will be much more expensive if it is implemented at the block level.

When you enter a function in JavaScript, an object is highlighted (well, a couple, but we will focus on one), which becomes a "variable object" - i.e. where all arguments and local vars are stored for calling this function (as properties). This is the object that actually uses closure (and not just the โ€œcharactersโ€ that it seems to use, this is a common misconception). These objects are combined in a chain called the scope chain, which is used to resolve unqualified characters.

Imagine how much more would be if each block introduced a new area.

+5
source share

I would like to see examples of using a functional level area that would be more difficult or impossible to implement using a block level area.

This may sound obvious, but you can implement recursion in the area of โ€‹โ€‹the functional level, which can often be 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); 

This is almost impossible to implement with a block level area.

In the above example, a function will be executed first, passing it the value of the external variable x , before the function is called, a new execution context will be set up, which initializes a new lexical region, where y formal parameter associated with it.

After that, the function expression is executed again. -if y not 0 - initialization at each execution of a completely new lexical area.

+3
source share

There is nothing that you cannot do - it is easy to model the scope of the level with the scope of the block level or vice versa.

Conditional function declarations would be more inconvenient:

 if (console && console.log) { function debug(msg) { console.log(msg); } } else { function debug(msg) { alert(msg); } } debug('foo'); // does not work with block scope 
-one
source share

All Articles