Foundations of Javascript - Scope
Scope
- The current context of execution, which values and expressions can be referenced. If they are not in the scope then it won't be available to use. Child scopes can access parent scopes, but not vice versa
- Global Scope: Default scope for all code running in script mode.
function exampleFunction() {
testVar = "Inside Scope of Function"
}
exampleFunction()
console.log(testVar)
- Module Scope: Scope running in module mode
- Function Scope: Scope created with a function. Variables inside of function can't be accessed outside of function.
function exampleFunction() {
const testVar = "Inside Scope of Function"
console.log(testVar)
}
console.log(testVar)
Emptiness
- Undefined: Variable that has been declared but has no value.
- Undeclared: Variable that was not declared anywhere
- Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.
- Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.
- Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).
Function Expressions
- Function keyword can be used to define a function inside of expression.
- Anonmyous Functions and Named Functions
const clickHandler = function(){
}
const clickHandler = function handler() {
}
const clickHandler = function() {
}
const clickHandler = () => {
}
- Functions that execute as soon as it's defined.
- Used so it doesn't pollute the global namespace. Encapsulates functionality inside of the IIFE.
const firstVar = "Initial Value"
(() => {
console.log("Hello")
const firstVar = "David"
})();
console.log(firstVar)
Block Scoping
- Using let, function, class and const prevents a variable from polluting the global namespace, so that variables inside of the block statement won't affect same named variables in global scope.
const firstVar = "David"
{
const firstVar = "Tom"
console.log(firstVar)
}
console.log(firstVar)
Closure
- "Closure is when a function remembers the variables outside of it, even if you pass the function elsewhere"
- Gives access to outer scope Variables inside of a function
function init() {
var name = "Mozilla";
function displayName() {
console.log(name);
}
displayName();
}
init();
const ask = (name) => {
return () => {
console.log(name)
}
}
const myName = ask("David")
myName();