I have been programming in JavaScript
for a few months mostly using jQuery
. I understand closures and I have used them, however, I still can’t understand what is the difference between function level scope and block level scope in other languages such as C#. I have been trying to teach myself with no result on that subject. Could somebody explain me with some simple examples?
Function scope: Variables that are declared inside a function are called local variables and in the function scope. Local variables are accessible anywhere inside the function. Block scope: Variable that is declared inside a specific block & can't be accessed outside of that block.
Unlike functions, they can't stand alone. A block is a chunk of code that can be invoked kind of like a function, but not quite like one: a block only appears adjacent to a function call such as . each , and that function may or may not use that block by “invoking” it (executing the code inside it).
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 Level Scope: This scope restricts the variable that is declared inside a specific block, from access by the outside of the block. The let & const keyword facilitates the variables to be block scoped. In order to access the variables of that specific block, we need to create an object for it.
Prior to ES6 (the current version of JavaScript), JavaScript had only function level scope. That is, the following:
function foo() {
console.log('before block: ' + bar); // prints 'undefined'
if(true) {
var bar = 1;
console.log('inside block: ' + bar); // prints 1
}
console.log('outisde block: ' + bar); // prints 1
}
Is exactly equivalent to:
function foo() {
var bar;
console.log('before block: ' + bar); // prints 'undefined'
if(true) {
bar = 1;
console.log('inside block: ' + bar); // prints 1
}
console.log('outisde block: ' + bar); // prints 1
}
(As a matter of fact, what I've just shown is called "hoisting", which is exactly what JavaScript does: all variable declarations are hoisted to the top of the function; assignments are left where they are.)
In contrast, languages like C# have block level scope. This would result in a compile error:
public void Foo() {
if(true) {
var foo = 1;
Console.WriteLine("inside block: " + foo);
}
Console.WriteLine("outside block: " + foo); // WILL NOT COMPILE
}
But you can have this:
public void Foo() {
var foo = 1;
if(true) {
foo = 2;
Console.WriteLine("inside block: " + foo); // prints 2
}
Console.WriteLine("outside block: " + foo); // prints 2
}
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