There are three types of scopes in JavaScript.
- Global Scope
- Function Scope
- Block Scope
Global Scope
A variable declared outside a JavaScript function has a global scope. Such a variable is accessible by all functions and scripts on the page.
var language = "English";
// Variable 'language' is accessible here
function myFunction() {
// Variable 'language' is accessible here
}
// Variable 'language' is accessible here
Function Scope
A variable declared inside a JavaScript function has a function scope. Such a variable is accessible only within the function and is considered to be local to that function.
// Variable 'language' is NOT accessible here
function myFunction() {
var language = "English";
// Variable 'language' is accessible here
}
// Variable 'language' is NOT accessible here
Block Scope
A variable declared inside a block { } has a block scope. Variables or constants declared with let or const keywords can have the block scope.
// eg. block scope
{
let language = "English";
}
// Variable 'language' is NOT accessible here
Variables declared with var keyword cannot have block scope.
// eg. var
{
var language = "English";
}
// Variable 'language' is accessible here