- JavaScript variable scope is always function scope.
- When you defined a variable using var, then it will search the variable from current its point to top of the code. If found then ok else create new variable.
- here line number7: define variable z at the top means inside window object(global object).
- Line number4: define variable at the top of function x, because javascript work on function scope. It's not overwrite the variable z(in window) with z(present in function x) because they are not in same function.
- line number 3: when you try console.log(z), then it will search for that variable from current point, it found this in x function, so value of z in x function is 20
1. function x(){
2. function y(){
3. console.log(z);
}
4. var z = 20;
5. y();
}
6. var z = 25;
7. x()
If I rewrite the code like
function x(){
function y(){
console.log(z);
}
y();
}
var z = 25;
x()
VM220:3 25
Now output will be 25, because it will find z inside window object, which value is z
This concept known as "Scope Chaining"