POLP (The Principle of Least Privilege) states components of a system should be designed to function with least privilege, access & exposure. This makes the overall system stronger from a security standpoint. A compromise or failure of 1 piece has a minimized impact on the rest of the system. Other benefits include avoiding naming collisions, unexpected behaviour & unintended dependencies. For each piece, default to exposing the minimum. Keep everything else private. A scope enables control of a declaration's exposure.
.js file is being imported into a
.html file, its outer most scope is the global scope. Although the function arguments are highlighted, they aren't included in the global scope. Details below.
Function & block scopes are between the
This means a function's arguments aren't within a function's scope.
They aren't in a function's parent scope either.
When compiled, the location of arguments can be thought of as being in a new scope that wraps the function.
This is why
const can't be used in a
It needs to be re-assigned after the 1st iteration via
Accessing Variables & Functions
When a reference cannot be found within a scope, the parent scope is searched.
If it still can't be found, the next parent scope is searched.
This continues until the reference is found or there are no more scopes to search.
At that point, a reference error will be thrown.
Below is an example of a variable that is declared in the global scope but accessed from a function scope.
The engine 1st searches the function scope for
It can't find it, so it then searches the parent scope & finds the declaration.
The global scope is where:
- ▪ The environment hosting the JS engine exposes its own built-ins:
- ▫ the DOM (
- ▫ timers (
- ▫ web platform APIs: navigator, history, geolocation, WebRTC, etc.
If the environment is the browser.
function declaration in the global scope will be added to the global object.
This object is commonly accessed through
However, it is better to use the standardized reference
- ▪ is invoked as soon as it is defined,
- ▪ doesn't pollute the global namespace &
- ▪ can't be invoked again.