In reading over the try/catch/finally documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch and testing some code, a question arises that I’d appreciate receiving clarification on. I may likely just be missing the obvious.
In the code and output in the example below, the value of variable z is assigned in the finally block just as x is, but the value of variable y logged after the function update runs does not reflect that assignment and is ‘try’ rather than ‘finally’. It appears that the finally block processes before the function returns but the value of the return is set prior to that and remains what it was at the point it occurs in the code and no longer depends on the value of z after that point.
If this is true and is consistent, and if the variables used here were local to the function update rather than global, is the finally block a reliable place to set a large return variable to null in order to avoid a memory leak? In other words, if z were very large and returned, and for some reason was not recognized for garbage collection, would setting it to null in the finally statement be a reliable method of releasing the memory after the return of it?
Thank you.
let y, z, x = 'initiated';
function update() {
try {
x = z = 'try;
return z; }
catch(e)
{ console.log(e); }
finally {
x = z = 'finally';
console.log('z in finally : ' + z ); } // 'finally'
} // close update()
console.log( 'x before update : ' + x ); // 'initiated'
y = update();
console.log( 'x after update : ' + x ); // 'updated'
console.log( 'y after update : ' + y ); // 'try'
console.log( 'z after update : ' + z ); // 'finally'
Output in order is:
x before update : initiated
z in finally : finally
x after update : finally
y after update : try
z after update : finally