Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript scope in a try block

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?

like image 292
user5243421 Avatar asked May 04 '12 02:05

user5243421


People also ask

Do try catch blocks have scope?

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.

Is there block scope in JavaScript?

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.

Is try catch scoped?

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.

Can you return in TRY block JavaScript?

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.


Video Answer


1 Answers

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); } 
like image 131
DrEnter Avatar answered Sep 22 '22 10:09

DrEnter