Tuesday, November 6, 2018

TypeScript - ES6 - block scope

To understand block scope, Consider the following code:
let var4reset = "hello";

// Block Scope test
function resetMyVariable (){
console.log("before == "+var4reset);
let var4reset = null;
console.log("after == "+var4reset);
}

console.log("variable out before call == "+var4reset);
resetMyVariable();
console.log("variable out after call == "+var4reset);


Its console output is generated as:
variable out before call == hello
city-App.ts:10 before == undefined
city-App.ts:12 after == null
city-App.ts:17 variable out after call == hello

We can see that the variable which is defined outside the function, does not hold the same value inside the function during the call. This is because, function has its own scope. Scope defines where a variable lives. It is the jurisdiction in which the variable operates.

If you want the variable value to be available inside the function, then you need to pass to the function using function arguments. Also, the function defined inside the function does not live outside it. This is block scope of the variable.

Refer:









No comments:

Post a Comment