Say I'm trying to execute this JavaScript snippet. Assume the undeclared vars and methods are declared elsewhere, above, and that something
and somethingElse
evaluate to boolean-true.
try { if(something) { var magicVar = -1; } if(somethingElse) { magicFunction(magicVar); } } catch(e) { doSomethingWithError(e); }
My question is: what is the scope of magicVar
and is it okay to pass it into magicFunction
as I've done?
Try-Catch and Variable Scope -it is not available to the scope outside. We would have the same problem if we tried to return the price inside of the catch block. Here's a key point: Variables declared inside a try or catch block are local to the scope of the block.
Block Level Scope: This scope restricts the variable that is declared inside a specific block, from access by the outside of the block. The let & const keyword facilitates the variables to be block scoped. In order to access the variables of that specific block, we need to create an object for it.
Variables declared within the try/catch block are not in scope in the containing block, for the same reason that all other variable declarations are local to the scope in which they occur: That's how the specification defines it. :-) (More below, including a reply to your comment.) Note the difference.
The return 10 in the try block will not be reached because we throw a Return error before reaching the return statement. Now, the catch block will catch the Return Error , and the return 20 will not be considered because there is a finally block present. Upon executing the finally block, the return 30 will be returned.
Lots of other good answers about how Javascript handles this with var
, but I thought I'd address the let
situation...
If a variable is defined with let
inside the try
block, it will NOT be in scope inside the catch
(or finally
) block(s). It would need to be defined in the enclosing block.
For example, in the following code block, the console output will be "Outside":
let xyz = "Outside"; try { let xyz = "Inside"; throw new Error("Blah"); } catch (err) { console.log(xyz); }
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