JavaScript Buzzwords: Closures, Hoisting, Currying, Event Loop, Bind/Call/Apply
1. Closures
JS by itself is not a language that is OOPS friendly. In order to mock the Abstraction/Encapsulation in the traditional OOPS, closures are used. A closure is just a pattern of writing a function (here function is treated as a “class”)
Without Closures:
No matter how many times you call CounterTest(), the count value is always “generated” fresh and hence count always increments from 0 and returns 1.
But, what if you had to preserve the count value and on each call, it had to increment based on the previous result.
Ex:
Closure to the rescue!
With Closures:
Summarizing:
· Child function has access to parent function’s private variables.
· Parent function returns the child function and
only exposes this to the outside world (Abstraction/Encapsulation)
· Outside functions are not allowed to directly “touch”
these private variables. Instead, the variables are accessed through the child function that is exposed
2. Hoisting
3. Currying
It is a technique for converting function calls with multiple arguments into chains of function calls with a single argument for each call, but JavaScript supports multiple arguments in a single function call.
The gist is that, have some logic that will be applied to two or more arguments, and we only know the value(s) for some of those arguments. Currying can be used here to fix those known values and return a function that only accepts the unknowns, to be invoked later when we actually have the values you wish to pass. This provides a nifty way to avoid repeating yourself when you would have been calling the same JavaScript built-ins over and over with all the same values but one.
4. Event Loop
Call Stack: It records where exactly in the program we are. When we step into a function, it is pushed into the stack and when we return from a function, it is popped out of the stack
WebAPIs: Browser is more than just a runtime. Apart from runtime, Browser contains things like document (DOM), Ajax (XMLHttpRequest), setTimeout() etc. Because of this, JS supports asynchronous behavior and allows concurrency.
Task Queue: After an async job is completed running in WebAPI, it moves to "task queue"
Event Loop: Does one simple job. It looks at the task queue and the stack. If the stack is empty, it pushes the first thing in the Task Queue onto the Call Stack.
Scenarios:
Scenario 1: With setTimeout({...},0): setTimeout with 0 is done to execute a piece of code when the stack is clear
Scenario 2: With setTimeout() and buttonClick() event
Scenario 3: Multiple setTimeout()
Scenario 4: Async Array with Sync

Comments
Post a Comment