Member-only story
Why Do Some Variables in JavaScript Return ‘undefined’ or Cause a ‘ReferenceError’?
A Comprehensive Guide
Table of contents
Introduction
Have you ever wondered why variables declared in one part of your JavaScript code aren’t accessible from another part? That’s because of the concept of scope in JavaScript.
Scope refers to the accessibility of variables and functions in your code. In simple terms, scope determines where your variables and functions are visible and accessible. It is defined by the location in your code where the variable or function is declared. Understanding scopes is crucial in JavaScript as it can affect the behaviour of your code and lead to unexpected results if not handled properly.
For instance, a variable declared outside a function has global scope and can be accessed from anywhere in your code, while a variable declared inside a function has local scope and can only be accessed within that function.