Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  157] [ 6]  / answers: 1 / hits: 38097  / 12 Years ago, fri, may 4, 2012, 12:00:00

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?


More From » scope

 Answers
90

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);

[#85804] Thursday, May 3, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brandon

Total Points: 393
Total Questions: 106
Total Answers: 106

Location: Aland Islands
Member since Wed, Nov 17, 2021
3 Years ago
;