Long time APCS-A/AB teacher who learned to love JavaScript (sort of).
Short version: in JavaScript there are only two scopes: global and local. And, unlike Java, local scope in JavaScript only applies to functions (and objects).
So this:
if( someVal == true)
{
var x = 10;
}
console.log(x);
is equivalent to:
var x; //declared but undefined
if( someVal == true)
{
x = 10;
}
console.log(x)
The term for this behavior and behind-the-scenes code rearrangement is called “hoisting” - As in variables that are declared and/or initialized inside loops, if statements, etc. are “hoisted” up out of there and into the global scope space.
In most cases this is actually convenient, or at the very least allows you to get away with some carelessness. For example, you can redeclare a variable later in the program - or at least you can appear to. Really it will just re-assign a value to the already declared variable that’s in the global space.
Your classic function examples for scope from Java will still apply in JavaScript. Namely function params are local to the function, not to mention any other vars declared inside the function. For example, here’s a doozy (meant to obfuscate - DON’T WRITE CODE LIKE THIS!) what does this display to the console? (the code is commented to explain the answer)
var foo = 7;
var a = 7;
myFunc(foo); //call myFunc
console.log(foo);
console.log(a);
function myFunc(a){ //myFunc definition
foo = 0; // sets global foo to 0
a = 0; // a is a param and LOCAL to the function
// so a is set to 0 and the global a is untouched
}
It will display 0
and 7
- the values of foo
and a
respectively after the function has run.
Now here’s the doozy. Same program with one difference - see how foo
is redeclared inside the function.
var foo = 7;
var a = 7;
myFunc(foo); //call myFunc
console.log(foo);
console.log(a);
function myFunc(a){
var foo = 0; // declares a LOCAL foo for myFunc
a = 0; // sets LOCAL param a to 0, global a is untouched
}
Now this will print 7
and 7
since the global variables foo
and a
were unaffected by running the function.
Actually, which one of these two examples is the bigger gotcha depends on what you were trying to do in the first place.
Hope this helps.
p.s.
FWIW my impression is that this WILL NOT be an issue that is tested on the CSP exam. That is variable scope is not an issue. I believe this because scratch, I think, but certainly App Inventor (which are popular languages for CSP) don’t have local scope.