Member-only story
In the world of JavaScript, understanding the concept of scope is crucial for writing efficient and maintainable code. Two types of scope play a significant role: function scope and block scope.
In this article, we’ll dive deep into the intricacies of each and explore how they impact variable accessibility and program flow.
Function Scope: The Traditional Approach
Function scope has been a fundamental concept in JavaScript since its inception. Within a function, variables declared with the var
keyword are accessible throughout the entire function body, including any nested functions. However, these variables are not accessible outside the function in which they are defined.
function outerFunction() {
var outerVar = 'I am outside';
function innerFunction() {
var innerVar = 'I am inside';
console.log(outerVar); // Output: 'I am outside'
}
innerFunction();
console.log(innerVar); // Uncaught ReferenceError: innerVar is not defined
}
outerFunction();
console.log(outerVar); // Uncaught ReferenceError: outerVar is not defined