Member-only story

Mastering Function and Block Scope in JavaScript: A Practical Guide

Unravel the mysteries of scope and take your JavaScript skills to new heights

Max N
3 min readMar 18, 2024
Photo by Esther Jiao on Unsplash

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

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet