I saw a piece of code in a book, which is as follows:
x = 10;
if(x ==10) { // start new scope
int y = 20; // known only to this block
x = y * 2;
}
Are both, scope and block, the same?
In a browser environment, the global scope is controlled by the window object while in Node. js, it's controlled by the global object. Block scopes are what you get when you use if statements, for statements, and the like.
Block scoping means declaring a variable, not just inside a function, but around any curly brackets like if statements or loops. The variable itself let i is still in memory, but the engine just won't allow you to access it like before when we used var.
The scope determines the accessibility of variables and other resources in the code, like functions and objects. JavaScript function scopes can have two different types, the locale and the global scope. Local variables are declared within a function and can only be accessed within the function.
There are three types of scope in JavaScript — 1) Global Scope, 2) Function Scope, and, 3) Block Scope.
From Mozilla's A re-introduction to JavaScript (JS Tutorial)
An important difference between JavaScript and other languages like Java is that in JavaScript, blocks do not have scope; only functions have a scope. So if a variable is defined using var in a compound statement (for example inside an if control structure), it will be visible to the entire function. However, starting with ECMAScript 2015, let and const declarations allow you to create block-scoped variables.
Given the examples for var and how they differ from those for int and const, we can gather that, in JavaScript, a variable declared with var is visible outside of its immediate "scope," as we would typically use the word in other languages.
In the example given, something declared with var in a for-loop is available from anywhere in the function, both before and after the for-loop in which it was declared.
// myVarVariable *is* visible out here
for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) {
// myVarVariable is visible to the whole function
}
// myVarVariable *is* visible out here
This is in contrast to anything declared with let and const, which are limited to the block in which they are declared, in much the way variables are limited to the immediate scope of a single set of curly braces { } in other languages.
Moral of the story: be careful with var if you are used to other languages. It is much more powerful and visible than you would expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With