JavaScript Scope

What is "scope" and how does it work in JavaScript?

Scope defines the specific range, that effects certain code. In JavaScrip there is Global Scope, Local, Scope and Block Scope.

  • Global Scope: refers to variables outside of a function.
  • Local Scope: refers to variabls defined within a function.
  • Block Scope: Exists only when variable are defined by the "let" or "cont" keywords.

Variabls defined in global scope (outside of functions) can be seen throughout the entiriety of the code, and can therefore be changed by other lines of code. For example if I were to right "var number = 2" then "var number = 3" the number variable would now be 3.

Variabls defined in local scope (within functions) can only be seen by code within that function. Therefore code outside of the function can not change what is happening within the function. If I were to write "var number = 2" outside of a function, and "var number = 3" inside of a function, then my number variable in global scope would still be 2, and the number variable inside the function would still be 3.

Variabls defined in Block Scope, must be defined with "let" or "cont" and surrounded by braces {}. When this occurs The variables can change as you move from one set of {} to another. Imagine the {} to be functions defining local scope, as above. The variables only care about code in there own function or {} and won't change as the result of outside code. However, variables defined with the "var" keyword are not a part of block scope and therefore can be changed by code outside of {} of which it was defined.

father and son, looking down a high-tech telescope