Scope is a concept that refers to where values and functions can be accessed.
Various scopes include:
- Global scope (a value/function in the global scope can be used anywhere in the entire program)
- File or module scope (the value/function can only be accessed from within the file)
- Function scope (only visible within the function),
-
Code block scope (only visible within a
{ ... }
block)
Global Variables
// Variable declared globally
const color = 'blue';
function printColor() {
console.log(color);
}
printColor(); // Prints: blue
JavaScript variables that are declared outside of blocks or functions can exist in the global scope, which means they are accessible throughout a program. Variables declared outside of smaller block or function scopes are accessible inside those smaller scopes.
Note: It is best practice to keep global variables to a minimum.
Block Scoped Variables
const isLoggedIn = true;
if (isLoggedIn == true) {
const statusMessage = 'User is logged in.';
}
console.log(statusMessage);
// Uncaught ReferenceError: statusMessage is not defined
const
and let
are block scoped variables, meaning they are only accessible in their block or nested blocks. In the given code block, trying to print the statusMessage
using the console.log()
method will result in a ReferenceError
. It is accessible only inside that if
block.
Block scope is a powerful tool in JavaScript, since it allows us to define variables with precision, and not pollute the global namespace. If a variable does not need to exist outside a block— it shouldn’t!
Scope Pollution
Scope pollution is when we have too many global variables that exist in the global namespace, or when we reuse variables across different scopes. Scope pollution makes it difficult to keep track of our different variables and sets us up for potential accidents.
let num = 50;
const logNum = () => {
num = 100; // Take note of this line of code
console.log(num);
};
logNum(); // Prints 100
console.log(num); // Prints 100
Even though the reassignment is allowed and we won’t get an error, if we decided to use num
later, we’ll unknowingly use the new value of num
.
Top comments (0)