user5243421 user5243421 - 1 year ago 84
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

evaluate to boolean-true.

try {
if(something) {
var magicVar = -1;

if(somethingElse) {
} catch(e) {

My question is: what is the scope of
and is it okay to pass it into
as I've done?

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download