<script>
let value = 10;
function start() {
name = 'Bippan'
console.log(value) // prints 10
}
start();
console.log(name) // prints Bippan
</script>
Scopes in Javascript.
Global Scope
Variables declared outside function scope, module scope or block always has global scope.
Example
Global variables can be accessed from anywhere when written in script tag.
Variables declared without any var keyword is by default set as global variable.
Function Scope
Variables defined inside function including parameters has function scope access, variables inside function cannot be accessed outside function.
Example
function start(name) {
let value = 10;
console.log(name); // bippan
console.log(value); // 10
}
start("bippan");
console.log(name); // ReferenceError: value is not defined
console.log(value); // ReferenceError: value is not defined
Block Scope
Scope created with the curly pair of braces has block scope.
Variables declared with let and const has block scope.
Example
let a = 10;
{
let a = 20;
}
console.log(a); // 10
const b = 30;
{
const b = 40;
}
console.log(b); // 30
var c = 50;
{
var c = 60;
}
console.log(c); // 60
Lexical Scope
Scope in which the child function is created is the lexical scope of child.
A closure is formed for the inner functions to access the variables or functions written outside the function.
A closure is created everytime a function is created.
Example
function start() {
let value = 10;
function end() {
console.log(value); // 10
}
end();
}
start();
## Scope Chaining
Searching variables or functions in its outer scope is defined as scope chaining.
In terms of lexical scope, searching variables or functions in its lexical scope till it reaches outer most scope is called scope chaining.
let value = 10;
function start() {
let name = "bippan";
function end() {
console.log(value); // 10
console.log(name); // bippan
}
end();
}
start();