Understanding scope
Scope is a fundamental concept in programming that determines the visibility and accessibility of variables in different parts of your code.
Why
To expand on the above, scope exists because we don’t want to allow all parts of the code to see some variables and we don’t want to make a mess. Imagine if all of your variables were global, how would you name them(they must be unique), how would you pass them in specific parts of the code, how would you know how and when a variable is changed througout the code and a lot more messy things. Apart from our codebase being messy it would also negatively impact our performance because our variables would be long lived and they would (probably) not be garbage collected(in simple terms purged from memory). When a function or block of code finishes executing, any variables or objects created within that scope become eligible for garbage collection if there are no remaining references to them.
Global Scope
Variables declared outside of any function or block have global scope. They can be accessed from anywhere in your code.
let globalVar = "I am global";
function printGlobal() {
console.log(globalVar);
}
console.log(globalVar); // Outputs: "I am global"
printGlobal(); // Outputs: "I am global"
Function Scope
Variables declared within a function have function scope. They are only accessible within that specific function.
function myFunction() {
let localVar = "I am local";
console.log(localVar);
}
myFunction(); // Outputs: "I am local"
console.log(localVar); // Throws an error: localVar is not defined
Block Scope
ES6(⏭️) introduced block scope with the let
and const
keywords. Variables declared with let
and const
are confined to the block where they are defined.
if (true) {
let blockVar = "I am in a block";
console.log(blockVar);
}
console.log(blockVar); // Throws an error: blockVar is not defined
Nested Scope
Variables declared in an outer scope are accessible within inner scopes, but the reverse is not true.
let outerVar = "I am outside";
function outerFunction() {
let innerVar = "I am inside";
console.log(outerVar);
console.log(innerVar);
}
outerFunction(); // Outputs: "I am outside" and "I am inside"
console.log(innerVar); // Throws an error: innerVar is not defined
Object Scope
Objects in NodeJS can have their own scope, encapsulating properties and methods within the object.
const outsideVar = "visitor";
const person = {
name: "Alice",
greet: function () {
console.log(`Hello, ${outsideVar}!`);
},
};
person.greet(); // Outputs: "Hello, visitor!"
console.log(person.name); // Outputs: "Alice"
What now?
Experiment with how scope behaves in different situations.