Scope and closures are fundamental concepts in JavaScript that influence how variables and functions behave in our code. Understanding scope is key to knowing where variables can be accessed, while closures can be used in maintaining state and context in our functions. Together, these concepts form the backbone of many advanced patterns, including those used in React.

Understanding scope

Scope determines where variables are accessible in our code. JavaScript has three types of scope:

  • Global: Variables declared outside any function or block exist in the global scope, making them accessible throughout the code.

  • Function: Pertains to variables declared inside a function, which can only be accessed within that function.

The following example demonstrates the concept of global and function scope.

Get hands-on with 1400+ tech skills courses.