## What is Scope?
Scope in JavaScript refers to the accessibility or visibility of variables. That is, which parts of a program have access to the variable or where the variable is visible.
### Why is Scope Important?
1. The main benefit of scope is security. That is, the variables can be accessed from only a certain area of the program. Using scope, we can avoid unintended modifications to the variables from other parts of the program.
2. The scope also reduces the namespace collisions. That is, we can use the same variable names in different scopes.
## Types of Scope
There are three types of scope in JavaScript —
1. Global Scope
2. Function Scope
3. Block Scope
## Global Scope
Any variable that’s not inside any function or block (a pair of curly braces), is inside the global scope. The variables in global scope can be accessed from anywhere in the program. For example:
```sh
var greeting = 'Hello World!';
function greet() {
console.log(greeting);
}
// Prints 'Hello World!'
greet();
````
## Local Scope or Function Scope
Variables declared inside a function is inside the local scope. They can only be accessed from within that function, that means they can’t be accessed from the outside code. For example:
```sh
function greet() {
var greeting = 'Hello World!';
console.log(greeting);
}
// Prints 'Hello World!'
greet();
// Uncaught ReferenceError: greeting is not defined
console.log(greeting);
```
## Block Scope
ES6 introduced let and const variables, unlike var variables, they can be scoped to the nearest pair of curly braces. That means, they can’t be accessed from outside that pair of curly braces. For example:
```sh
{
let greeting = 'Hello World!';
var lang = 'English';
console.log(greeting); // Prints 'Hello World!'
}
// Prints 'English'
console.log(lang);
// Uncaught ReferenceError: greeting is not defined
console.log(greeting);
````
We can see that var variables can be used outside the block, that is, var variables are not block scoped.
## Lexical Scope
Lexical Scope (also known as Static Scope) literally means that scope is determined at the lexing time (generally referred to as compiling) rather than at runtime. For example:
```sh
let number = 42;
function printNumber() {
console.log(number);
}
function log() {
let number = 54;
printNumber();
}
// Prints 42
log();
```
Simply put, a lexical environment is a place where variables and references to the objects are stored.
Note — Don’t confuse lexical scope with the lexical environment, lexical scope is a scope that is determined at compile time and a lexical environment is a place where variables are stored during the program execution.