Kontext
Function scope, var, let and const
We have spoken a bit regarding scope when we were explaining the var keyword alongside with a return function statement.
In JavaScript, not all values and variable are accessible from everywhere. Some of them they are only accessible inside the function that were defined. Other variables are accessible only inside the block scope they were defined (inside a loop's body etc). That means, that each variable's scope can vary, depending on how and where it was initially declared.
In JS there are 4 ways to create and define a new variable.
1. Without a keyword! For example: a = 20; That means that a new variable will be created with the value of 20. If you create a variable like that ( you shouldn't but that's another story), the a variable is accessible from EVERYWHERE in your script regardless of where has been declared. That is because the a variable's scope is the GLOBAL SCOPE!
2. By using the var keyword: For example: var a = 20; That means that the a variable is accessible inside the whole function it was created. Var keyword's scope is the function scope. Take notice: If a was created on the global execution context then a variable is global (since the whole script is the function that wraps it!)
3. By using the let keyword: For example let a = 20; That means that a is accessible only inside the block of code (the curly braces) that was created. For example if you have declared the let a = 20; inside an if statement, then you have access to a variable's value only inside this if block! This is called block scope.
4. By using the const keyword: const a = 20; Exactly like let, block scope, but re-assignment of a new value is NOT allowed. A is a const, that means it's value is subject to no changes.
If you want to learn more about scope, var, let, const and a procedure that is called hoisting, you can do so here