Remember being a kid and building sand castles at the beach? Only to come back after a few hours and see the whole thing being washed away? The issue was with the foundation. Turns out sand doesn't really stick together for long, particularly if you add water. This is exactly what most developers are trying to do these days and at times I have found myself guilty as charged... Learning framework after framework, constantly adding new things on top of weak foundations. But, no matter how tall the castle is, if the foundations are built of sand, they will be washed away in a matter of seconds.
- Local Scope allows access to everything within the boundaries (inside the box)
- Global Scope is everything outside the boundaries (outside the box). A global scope can not access a variable defined in local scope because it is enclosed from the outer world, except if you return it.
Example: The code given below will give you an error because “name” is defined within the boundary (local scope) of the showName() function. You can not have access to this variable outside the function.
Now, take a look at the code given below and see how you can access the variable “name” defined in the local scope.
2. IIFE (Immediately Invoked Function Expression)
Example: Take a look at the code below.
Now what happens if we invoke our function before we declare it (with hoisting)
A closure is simply a function inside another function that has access to the outer function variable. Now, this definition sound pretty much straightforward but the real magic is created with the scope. The inner function (closure) can access the variable defined in its scope (variables defined between its curly brackets), in the scope of its parent function, and the global variables. Now here you need to remember that the outer function can not have access to the inner function variable (we have already discussed this in the scope concept). To sum it up: Closures can be defined in simple terms as “a function run, the function executed. It’s never going to execute again but it’s going to remember that there are references to those variables so the child scope always has access to the parent scope.”
A promise may be in three possible states…
- Fulfilled: When the operation is completed successfully.
- Rejected: When the operation is failed.
- Pending: initial state, neither fulfilled nor rejected.
7. Async & Await
- ES5 -> Callback
- ES6 -> Promise
- ES7 -> async & await
Example: Check out the below code.
To notify JS that we are working with promises we need to wrap ‘await’ inside an ‘async’ function. In the above example, we (a)wait for two things: response and posts. Before we can convert the response to JSON format, we need to make sure we have the response fetched, otherwise we can end up converting a response that is not there yet, which will most likely prompt an error.
I hope this helped you in some way. This leads me into a question: