Monday, June 27, 2022

Break for javascript debug in chrome when sending xhr/fetch request

It is helpful to check the server request and response in chrome for javascript code, particularly if you do not have the source code information available to set breakpoint in a particular lines.

For chrome, this is easy to do by opening the developer console, and then open source tab, on the right side panel, under the section title of "XHR/fetch Breakpoints", add a new break point item for "Any XHR or fetch". 

The breakpoints requests to input string to break on matched url. In order to break on any xhr or fetch requests, just set the input string as '.', note '*' does not work for matching all purpose.


Thursday, June 23, 2022

Closure for javascript

In MDN web doc , A closure in JavaScript is defined as:

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

The definition is not very clear as the closure involves both parent function and inner functions. So it needs more explanation about the definition:


When a (parent) function is executed, the function body will have all the local variables set to some value for the function execution. This execution environment including all the local variables is called parent function's lexical environment. 

If any inner function is defined within the parent function body, then the parent function's lexical environment will provide the variables defined in parent function, but referred by the inner function. Those variables are called closure variables.

The closure is created when the parent function is executed, and for each execution of parent function, a new closure environment is created. This makes sense, as each execution will have different variable values inside the parent function. All the inner functions defined in the parent function body, and whenever they are called, they will share the same lexical environment, i.e. the local variable's latest values declared in the parent function. 

So a closure is created when every time the parent function is executed, it captures all the local variables used by that execution instance. 

Note the closure only keeps the latest values of all the local variables defined in the parent function, so it the parent function does a for loop to update a local variable, then the local variable will have the latest value after the for loop finished. If a inner function is called later, then the inner function can only see the latest value of the parent function's closure variables, certainly the inner function can also update the closure variable to be visible to other inner functions.