Reputation: 1153
Can someone explain me the javascript block level scoping.
I am not able to replicate the below example given by w3schools;
Upvotes: 0
Views: 2532
Reputation: 53
Before the latest version of Javascript (ES6 / ES2015) was released, Javascript only had local scope and global scope. Here's an example of local scope:
function x(){
var y = 1
}
console.log(y) // undefined because y is in the local scope of function x
Here's an example of global scope:
var a = 1
function sayOne() {
console.log(a) // prints 1 because the "a" variable is global
}
So in the global scope, the variable is basically visible to everything else in the program, but in local scope, it is hidden and private from everything outside of the parent function.
As your screenshot shows, Javascript did NOT have block level scope. So the code that you provided will return i despite the fact that it is OUTSIDE of the for loop block.
for (var i = 0, i < 10) {
// some code here
}
return i // this will return i since i is global and will not be undefined
But with block scoping, the variable will only exist within that code block, such as with loops. Let's take a look at the same code, but with the ES6 block scoped "let", which works the same as "var" but has block scoping.
for (let i = 0, i < 10) {
// some code here
}
return i // this will now return undefined because i is only defined within
// the for loop
Upvotes: 1
Reputation: 962
Till ES5, JS does not support block
level scoping. By block
I mean any piece of code surrounded in {}
So if you were writing the same code in another block level language like C#,Java, C++, etc. the variable i
would have its life only for the region delimited by {}
of the for
loop. Outside the loop it would not have been accessible.
However, things are a bit different in the world of JS, or better to say, were different
before ES6 which allowed block level scope
ing using let
keyword.
So the code above is interpreted as
var i; // i is declared in the containing scope
for(i = 0; i < 10; i++) {
... // some code
}
return i; // therefore accessible here
Had this been block level scoped, i
would have not been accessible outside for loop for return.
for(var i = 0; i< 10; i++){
}
return i; // i is not accessible here in block scoped language
Upvotes: 0