Another scope related post: Function Scope in JavaScript for Beginners
Each variable has a scope that basically defines its boundary. A boundary that restricts the variable and sets the line(scope) in which part of the program the variable is going to be visible/callable/usable.
What happens when you define the variable inside a function?
Those variables’ scope is limited to that function only. They become local variables.
Every time you call that particular function, a new instance of that variable is created. So even if you have variables with same names in different functions, JavaScript allows it even though they are in a same program.
Just like this:
function a() {
var container = "a";
console.log(container);
}
function b() {
var container = "b";
console.log(container);
}
a(); //a
b(); //b
When you declare variables with let or const, they are local to the specific code block(for e.g. a loop). So, the code before the loop (or after the loop) doesn’t know about those variables.
So, you can’t make use of a variable declared with let or const outside of the function but you can use the variable declared with var.
Just like this:
let a = 10;
if (a == 10) {
let b = 20;
var c = 30;
console.log(a + b + c); // 60
}
console.log(b + c); // b is not defined
console.log(a + c); // 40
You can use the variable declared with var in another function just like this:
let a = 10;
if (a == 10) {
let b = 20;
var c = 30;
console.log(a + b + c); // 60
}
function sum() {
console.log(a + c);
}
sum(); // 40
function sum2() {
console.log(a + b);
}
sum2(); // b is not defined
What happens when you define the variable outside a function?
Those variables’ scope is the whole program, call/use them anywhere in the program. They become global variables.
What happens when the local and global variable both have the same name?
In that case, the local variable precedes. Just like this example:
let a = 10;
if (a == 10) {
let a = 20;
let b = 20;
var c = 30;
console.log(a + b + c); // 70
}
Nested scope
JavaScript has local and global scope but even inside the local there is sub-local(not an official word) scope.
Look at this example:
let a = 10;
function sum() {
let b = 20;
var c = 30;
console.log(a + b + c); // 60
sum2();
function sum2() {
var d = 40;
console.log(a + b + c + d); // 100
}
}
sum();
In the example above, sum2() function can see the variables defined outside of itself, in the outer function.
Now, look at the example below.
let a = 10;
function sum() {
let b = 20;
var c = 30;
console.log(a + b + c + d); // d is not defined, program will fail at this point
sum2();
function sum2() {
var d = 40;
console.log(a + b + c + d);
}
}
sum();
As you can see the outer function can not see the variable defined in the inner function. The whole concept called lexical scoping in JavaScript.
const let Scope var variables