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

Note: Any variables declared in JS but not yet assigned any value will have the value "undefined"
Ex: var a; console.log(a) //undefined

Any variable that is declared in JS (with keyword "var") inside any block (if/for/switch/while), internally JS moves the declaration to the top of the function 



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

  

After execution and the Call Stack is clear, event loop kicks in and pushes first thing on Task Queue to Call Stack
Summarizing:
console.log('Hi')
setTimeout(function cb() { console.log('there') }, 0 )
console.log('Test');
Output: Hi Test there

Scenario 2: With setTimeout() and buttonClick() event 



console.log('started');
$.on(button, 'click', function onClick() {
    console.log('Clicked')
});
setTimeout(function cb() { console.log('there') }, 5000 )
console.log('Done')

Output: 
started
Done
clicked //if u clicked before 5000 ms
there

Scenario 3: Multiple setTimeout() 

setTimeout(function cb() { console.log('Hi-1') }, 1000 )
setTimeout(function cb() { console.log('Hi-2') }, 1000 )
setTimeout(function cb() { console.log('Hi-3') }, 1000 )
setTimeout(function cb() { console.log('Hi-4') }, 1000 )
setTimeout(function cb() { console.log('Hi-5') }, 1000 )

Output:
Hi-1
Hi-2
Hi-3
Hi-4
Hi-5

Scenario 4: Async Array with Sync

Output:
1
2
3
4
a
b
c
d


5.       Bind / Call / Apply

They all allow to setting the value for this independent of how the function is called


When To Use Each

Use call() / apply() to invoke the function immediately. Call and apply are pretty interchangeable. Just decide whether it’s easier to send in an array or a comma separated list of arguments.
bind() returns a bound function that, when executed later, will have the correct context ("this") for calling the original function. So bind() can be used when the function needs to be called later in certain events when it's useful


JSFiddle code for reference: https://jsfiddle.net/5fyw1jas/1/

Comments

Popular posts from this blog

Inside the JavaScript Memory Box: Visualizing Variables, References, and Copies

React & State Management: All Concepts

React: Communication between components