Scope - TristanVarewijck/Block-Tech GitHub Wiki
Local scope
"Variables within a function become local to that function"
Local variables have function scope and can only be accessed within the function. (so if you call a variable with function scope outside of the function then it will give you an error and the variable will not run)
Code Example:
function run() {
// "run" function scope
let message = 'Run, Forrest, Run!';
console.log(message); // 'Run, Forrest, Run!'
}
run();
console.log(message); // throws ReferenceError
So the var message
will print by activating the run()
function because the function says to print it out but if we console.log(message)
outside of the function it will trow us an ReferenceError
.
Global scope
"A variabel declared outside of a function will become global."
A global variabel has global scope: All scripts and function can access it. (so basically variables under global scope can be accessed by everything because its "global")
Code example:
let favoriteFastfood = "cheeseburger";
function showCaseFastfood() {
console.log(favoriteFastfood);
}
showCaseFastfood()
console.log(favoriteFastfood);
In both cases the variable value from let favoriteFastfood
will print out.
NOTE about global scope
If we assign a value to a variable that has not been declared before it will automatically become global. I think this is better to explain if i show you with a code example:
Code example:
local scope:
myFunction();
function printMyName() {
myName = "Tristan";
console.log(myName);
}
The variable myName
is a global scope because it has never been declared before note that this variable is not declared with const
, let
or var
.
Resource
- A Simple Explanation of Scope in JavaScript | Dmitri Pavlutin (2020)
- JavaScript Scope | W3Schools
- Scope in JavaScript | TutorialsTeacher