When we talk about scope, we mean the visibility of one or more entities to certain parts of our code. For the purposes of this article, our entities are going to be limited to variables.
Global scope is pretty straightforward: Any variable defined outside any function or curly braces is part of the global scope and can be accessed from anywhere in the code.
Local scope is slightly more complicated. Any variable defined inside a
function declaration or curly braces can only be accessed inside the function or block of code it was declared respectively.
Okay, this is basically all you need to know about variable scope. Let’s look at some simple examples:
Block scope and definitions using
let keyword to clear up any remaining questions and doubts.
Closures are one of those things that might seem confusing at first, but really aren’t. A function defined inside another function is a closure. Closures are particularly useful when you want to access a variable defined inside a function’s scope from outside the function.
A practical use of closures could be defining a public set of functions that can get or set some private variables inside a function (which is a pretty common use-case in object-oriented programming). Here’s a pretty simple example of closures in action:
Scope refers to a variable’s accessibility. It can either be public (defined outside any functions and curly braces and accessible anywhere in the code) or local (defined inside a function or block and accessible only inside said function or block). Closures are functions defined inside other functions and can be used to access a function’s private variables from outside its own scope.
Create your free account to unlock your custom reading experience.