Scopes determine the accessibility of the variable. You can't access a variable from outside of its scope.
- Global Scope
- Local Scope (Function Scope)
Any variable declared outside of a block or function is inside Global Scope.You can access these variables from everywhere.
As the name suggests, variables declared inside the Function has Local Scope. They can only be accessed inside the Function.
ES6 introduces Let and Const variables that can be scoped to a block. So now there is one more type of scope.
Variables declared with Var has function scope. You can't access this variable from outside the function. However, if you declare variables inside the block with Var you can access it from outside.
Unlike Var, Let has block scope. You can only access these variables from inside the block. So if you try to access from outside it will give you Reference Error.
You can reassign the variable that declared with Var.
Var declarations (
var a) whenever they occur, they move up to the top of the file. This is called
hoisting.With this, you can do something like this. (You can read more about
hoisting if you click here)
With let you can't do this. It will give an error: