Scope defines where variables can be accessed or referenced. While some variables can be accessed from anywhere within a program, other variables may only be available in a specific context.
Scope is the context in which our variables are declared. We think about scope in relation to blocks because variables can exist either outside of or within these blocks.
const color = 'blue'; // <-- global
const returnSkyColor = () => {
return color; // blue
};
console.log(returnSkyColor()); // blue
When a variable is defined inside a block, it is only accessible to the code within the curly braces {}.
We say that variable has block scope because it is only accessible to the lines of code within that block.
const logSkyColor = () => {
let color = 'blue';
console.log(color); // blue
};
logSkyColor(); // blue
console.log(color); // ReferenceError
Having too many global variables can cause problems in a program.
When you declare global variables, they go to the global namespace. The global namespace allows the variables to be accessible from anywhere in the program. These variables remain there until the program finishes which means our global namespace can fill up really quickly.
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. For example, globally scoped variables can collide with other variables that are more locally scoped, causing unexpected behavior in our code.
let num = 50;
const logNum = () => {
num = 100; // Take note of this line of code
console.log(num);
};
logNum(); // Prints 100
// The reassignment inside logNum() affects the global variable num.
console.log(num); // Prints 100
It’s best practice to not define variables in the global scope.
Tightly scoping your variables will greatly improve your code in several ways:
const logSkyColor = () => {
const dusk = true;
let color = 'blue';
if (dusk) {
let color = 'pink';
console.log(color); // pink
}
console.log(color); // blue
};
console.log(color); // ReferenceError
Block scope is a powerful tool in JavaScript, since it allows us to define variables with precision, and not pollute the global namespace.