How to create scope?
We create scope by creating function.
Example 1:
var a = 42; //In global scope, could also just write as a = 42, omitting the var keyword, as we are in global scope
var b = 57; //In global scope
function example() {
var a = 10; //Attached to function
var b = 8; //Attached to function
console.log(a); -> 10
}
example(); -> 10
console.log(a); -> 42
Example 2:
function example() {
var a = 20;
function inner() {
a = 40; // Mutating the example() a, as we did't use var (Explanation below)
console.log("inner " + a); -> 40
}
inner();
console.log("outer " + a); -> 40 //Value is 40 as it was mutated by inner();
}
example();
If you're in a function thenvar
will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):
Example 3:
var a = 10;
function example() {
var a = 20;
function inner() {
var a = 30; //Bound to inner()
console.log("inner" + a); -> 30
}
inner();
console.log("outer" + a); -> 20
}
example();
console.log(a); -> 10
Example 4:
var a = 30;
function example(a) {
a = 20;
console.log(a); -> 20
}
example(a);
console.log(a) -> 30
For parameters that are passed in function, you can imagine that they are declared with the 'var' keyword.
Example 5:
Normally a compiled error in other languages such as Java..etc, but not Javascript.
function example() {
for (var i=1-; i< 10; i++) {
if(i > 5) {
var test = i * 10;
}
}
console.log(i + test); -> 10 and 90
}
Block statement does not create scope. Loops, switch, if, empty bracket {}..etc. It does not attach variable to the closest block, but to the closest function.