Scope of variables refers to the accessibility of a particular variable within the program.
- Global Scope
- Local Scope
- Block Scope
- Function Scope
Have a look at the different Scopes in detail.
What is Global Scope?
- Any variable declared outside of a function is said to have Global Scope.
- In simple terms, a variable that can be accessed anywhere in the program is known as a variable with global scope. Globally scoped variables can be defined using any of the three keywords: let, const, and var.
What is Local Scope?
- Any variable that you declare inside a function is said to have Local Scope. You can access a local variable can within a function. If you try to access any variable defined inside a function from outside or another function, it throws an error.
- Since you cannot access a local variable from outside the function, you can have a variable of the same name in another function as well.
What is Block Scope?
- The block scope does not work with the var keyword. You can either use let or const keywords for that.
What is Function Scope?
- Strict mode will throw an error if you try to use the same syntax after including "strict mode" in your program. It will help you in writing cleaner and more secure code.
- Just like variables, strict mode too can be used either globally or locally. If you write "use strict" at the program's start, it will be used globally. Otherwise, you can also use strict mode locally inside a function.
- All the modern browsers support Strict mode, except internet explorer 9 and its previous versions.
- A local variable lives until the function is under execution. The moment a function completes, the local variable gets deleted.
- A Global variable lives until the user closes the program or until the web browser is closed. However, if the user changes the window without closing the program, the global variable remains there.
- Where the variable declared
- How the variable declared