user5243421 user5243421 - 2 months ago 5
Javascript Question

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?

Answer

Javascript has function scope. That means that magicvar will exist from the beginning of the function it's declared in all the way to the end of that function, even if that statement doesn't ever execute. This is called variable hoisting. The same thing happens with functions declarations, which in turn is called function hoisting.

If the variable is declared in global scope, it will be visible to everything. This is part of the reason why global variables are considered evil in Javascript.

Your example will pass undefined into magicFunction if something is false, because magicVar hasn't been assigned to anything.

While this is technically valid Javascript, it's generally considered bad style and will not pass style checkers like jsLint. Extremely unintuitive Javascript like this will execute without any error

alert(a); //alerts "undefined"
var a;

POP QUIZ: What does the following code do?

(function() {
  x = 2;
  var x;
  alert(x);
})();
alert(x);
Comments