There are 4 types of scope in JavaScript: global scope, block scope, function scope, and module scope.
Global scope
The top-level scope in JavaScript is called the global scope. When you declare a variable in the global scope it’s going to be accessible in all your functions and code blocks.
var message = 'Hello, global scope!';
function logMessage() {
console.log(message);
}
To determine if your variable is global, check if it’s declared outside of any functions in your JavaScript file.
Block scope
Contrary to the global scope, you can declare variables in the code blocks.
The block scope has been introduced in ES6 alongside 2 important keywords: let
and const
.
let
allows you to declare a variable that can’t be accessed from outside the code
block it’s been declared in.
{
let message = 'Hello, block scope!';
console.log(message); // Hello, block scope!
}
console.log(message); // undefined or Reference Error: message is not defined
const
is the same as let
in terms of block scope visibility. The difference is that
you can’t reassign the value to the variable that’s been declared with const
.
const x = 5;
x = 8; // TypeError: Assignment to constant variable.
Variables created with var
don’t have the block scope.
{
let message = 'Hello, block scope!';
console.log(message); // Hello, block scope!
}
console.log(message); // Hello, block scope!
Function scope
In JavaScript each function creates a new scope. This means 2 things:
- you can’t access variables declared in one function from another function
function foo() { const message = 'Hello, function scope!'; console.log(message); // Hello, function scope! } function bar() { console.log(message); // ReferenceError: message is not defined }
- you can create variables with the same names in different functions
function foo() { const salary = `500k`; console.log(salary); // 500k } function bar() { const salary = `800k`; console.log(salary); // 800k }
Variables declared with var
, let
and const
behave the same (in terms of visibility)
when declared in function scope.
Module scope
Module scope is another invention that came to JavaScript with the ES6 standard.
It’s similar to the global scope. The only difference is that the module scope limits variable visibility to the module where it was declared.