https://scotch.io/tutorials/understanding-scope-in-javascript#toc-scope-in-javascript
When you start typing in JS you are in global scope.
Variables defined inside a function are in the local scope. Meaning they have a different scope for every call of that function.
Block statements
Contrary to the ‘var’ keyword, ‘let’ and ‘const’ support the declaration of local scope inside block statements.
Difference between let and const?
‘const’ is a signal that the identifier won’t be reassigned.
‘let’ is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm.
Both have block statement scope.
Context
Many developers think scope and context are the same thing. They are not. Scope is what we talked about previously. Context is ued to refer to the value of ‘this’ in some particular part of your code.
Scope refers to the visibility of variables and context refers to the value of ‘this’.
Lexical Scope
Means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope. This means that the child functions are lexically bound to the execution context of their parents. Lexical scope is sometimes also referred to as Static Scope.
Closures
Closures are closely related to Lexical Scope. A closure is created when an inner function tries to access the scope chain of its outer function. Closures contain their own scope chain, their parents, and the global scope.
When you return an inner function from a function, that returned function will not be called when you try to call the outer function. You must first save the invocation of the outer function in a separate variables and then call the variable as a function.
Key thing to note here is that ‘greetLetter’ can access the name variable in the greet function even after it has returned. One way to call the returned function without doing the variable assignment is to call it with () x2 like this.
Note: This still works.
The difference in the previous example is the return statement. It only gets invoked when you do the ()().
Public and Private Scope
JS doesn’t have concepts found public, protected, private. Instead it emulates these features using closures. Which is basically nothing more than locally scope variables and functions.
The Module Pattern
This module pattern is a way to define Objects (functions) in JS that exposes public methods via a return statement while keeping private methods inside.
Immediately-Invoked Function Expression (IIFE)
Changing Context with .call(), .apply(), and .bind()
Call and Apply functions change the context of the function you are calling.
The difference between .call() and .apply() is that in call you pass the arguments as a comma separated list, while in apply you pass them as an array.
Leave a comment