Variable declared inside the function (Locally) has Function Scope. Local variables can only be accessed from inside the function where they are declared. For example,
- Initialization during the declaration of a let variable is optional.
- A let variable will contain undefined if nothing is assigned to it.
let count; console.log(count); // Prints: undefined count = 10; console.log(count); // Prints: 10
- var is function scoped while let is block scoped
- The var keyword allows you to re-declare a variable without any issue. However, re-declaring a variable using the let keyword will result in an error.
- It can be said that a variable declared with var is defined throughout the program as compared to let.
- The var variables belong to the global scope or local scope if they are declared inside a function. The let variables are blocked scopes.
- The global var variables are added to the global object as properties. The global object is window on the web browser. However, the let variables are not added to the global object:
Function Scope var and let Example:
In the code snippet above, the above example uses var, note how var is declared in line 11, inside a block. This variable is known (but undefined) above the block. However, it is known and defined after the block.
The highlighted lines represent the areas where x has a scope. Since it is the entire function itself, var is said to have function scope.
Block Scope let and var Example:
The below example will highlight the block scope for let more clearly.
mango is declared as “yellow” in line7, and redeclared as “orange” in line 9 – inside the if block. However, as the output shows, the mango declared inside the if block has scope within that block only. Outside this block, the original mango variable set to “yellow” is available.
Conversely, in the code that uses var, re-declaration of mango to “orange” inside the if block, also changes the mango declared in line 7 to “orange“. This is because variables declared with var are defined globally, regardless of block scope.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.