Updated: Mar 25, 2020
The term scope describes the visibility of variables, functions, and objects in a line of code during runtime. The principle is based on the idea that users should only have access to what they need at that time—and it represents The Principle of Least Access in practice.
Software engineers should understand the difference between local scope and global scope. They should also be able to articulate which situations each access level is best for. Local scope refers to variables that can only be accessed by code inside of the function. On the other hand, global scope variables can be read and changed from anywhere in the code, regardless of the location of the variables.
Code typically runs in order from the first line to the last line. However, oftentimes scripts use conditional structures to change the way that code is executed.
Take a standard website contact form, for example. When a visitor completes the form and clicks submit, the script submits their information and generates a confirmation note for the user. However, if the form is not complete, the conditional structure will generate a note that one or more fields are required.