TypeScript Scope is JavaScript Scope
Explore how TypeScript handles variable scope similar to JavaScript, focusing on concepts like shadowing where variables overlap in different scopes, capturing which preserves variables in asynchronous functions, and the rules for declaring variables with var, let, and const. This lesson helps you understand best practices for managing scope to avoid errors and write clearer code.
We'll cover the following...
Shadowing scope
We briefly encountered the concept of scope when exploring the three declaration types discussed in the previous lessons. You saw that a variable declared using var has a broader than, let, and const. However, there are some other cases involving the scope with let and const.
The first case is shadowing. This occurs when one variable is declared twice, in an outer scope, and an inner scope. For example, if you have two loops and both of them are using the variable i, TypeScript is smart enough to understand that both declarations are for two different variables. However, it is confusing and susceptible to error, hence it is not recommended even if the code will transpile without a problem.
The code above will not allow the ...