What is scope?


#1

Question

What is scope?

Answer

scope is the context of code that determines the availability of parts of a program - including variables, objects, functions, etc - to another part of the program when the code is executed. If a variable/object/function/etc is not in the current scope that means it’s not available for reference or use.

For example:

let x = 1;

const myFunction = () => {
  let x = 2; //sets a `let` variable x to the value `2`
}
myFunction(); //calls myFunction 
console.log(x); //`1` is logged to the console because although there are two `let` variables that have the same name, the `let` variable inside the function is scoped to the block (in this case a function) it's in and the console.log outside of the function is not able to access the `let x` variable that is inside the function because it's scoped. 

Do note that this explanation and example is a very basic overview of scope. For a more detailed and in-depth explanation please check out the MDN documentation, other documentation, and tutorials for variables (in particular, how different variables are scoped), scope, and hoisting.


#2

Scope is the environment in which a value exists, and any references to that value. Scope exists along a chain. Nothing associated with the link above can gain access to that environment. There is no parent looking over this scope. It’s variables and constants are inaccessible to parent scope

The JavaScript interpreter is greedy and relentless. We should always keep this in mind. JS will look for a variable of the name written and if it finds it somewhere in the scope chain, use that value, legal or not.