Javascript T20 (Day 1)

Ayush Singh
6 min readNov 2, 2020

The power of a single thread that rules the software community is the most awesome thread ever witnessed. — Ayush Singh

JS is love!!

Table of Contents :-

(i) Why functions are special in JS

(ii) DRY with callbacks

(iii) black magic behind features like ‘once’, ‘memoize’, ‘maintaining states in async world’,

(iv) Event Loop :- how a single thread multitasks :P

(v) rescue from callback hells -> Promise

(i) Why functions are special in Javascript ?

Functions are the first class objects in JS. They can be treated like any other objects you can think of. This allows functions to be passed as an argument and also be returned by a function. WOW!!!

Eg :-

function being treated as object

(ii) DRY(Don’t Repeat Yourself) with callbacks :-

Suppose , you are given an array and you want to :-

(i) Multiply its elements with 2.

(ii) Divide its elements by 2.

(iii) Add its elements by 2.

Now, will you write 3 different functions to perform that task ??

To implement DRY. We can use callbacks :) Pass your operation in that function as an argument.

callbacks :- fns passed as an argument.

(iii) Closures :- The black magic of JS !!

When a function is called in JS, new execution context gets created that holds local variables and sequence wise execution of the function begins . After the execution, something is returned if required and the execution context is freed from the stack. This is basic programming, all know that. So what is special about closures ??????

Closures can help you still access some of the local variables even after the execution context is freed from the stack.(i.e) function returned but still somehow the local variables still hold . This is the secret behind ‘once’, ‘memoize’, ‘maintaining states ’.

HOW???? It all starts with returning a function!!!!!

Closure demistified

You see [[scopes]] :- it holds closure now. And that closure now holds closed over environment variables (C.O.V.E) . The data is persistent, lexically scoped and referenced.(P.L.S.R.D)

The local variables of iterate function are available in [[scope]]’s closure. We can’t access these variables directly now. Thus closure also provides abstraction to closed variables. The variables can now only be modified by calling the closure method.

calling fun(arr) everytime returns arr[i++]

Look at how fun(arr), uses closure.

(iv) Event Loop :

Let’s go through a code to understand this :

setTimeout confusing ??

As I have already mentioned JS is single threaded and executes code line by line, then why this strange behaviour??

Okay! so the thing is , there are some Browser APIs that javascript has access to . So what??

Some browser APIs that JS can use (setTimeout being one of them)

So whenever you use a browser API, JS asks the browser to execute it and once the browser finishes executing it , it pushes what has to be done after finish(eg:- print “first” after timeout of 1000ms) in a queue called callback queue.

What’s event loop then and what is its role ??

As I mentioned JS asks Browser to execute its APIs(eg: setTimeout) when it encounters one such, JS meanwhile continues executing next lines and doesn’t wait for the browser. Once the job is done by the browser , it starts pushing what has to be done next(eg:- print “first” after timeout of 1000ms) in callback queue.

Now comes the event loop,

event loop does the communication with the JS call stack and the callback queue. Once JS call stack is empty (i.e JS has finished executing everything till the end(eg:- console.log(“third”) ) , the event loop looks if anything is there in the callback queue and puts that in JS call stack and executes.

demonstration of event loop with call stack and callback queue

(v) Rescue from callback hells -> Promise

Asynchronocity is the backbone of modern web development.Earlier asynchronocity was handled only using callbacks.

Suppose I have to get an Image and when it is got I have to compress it and after compression I have to save the image.So, all these operations are kind of dependent and they can be asynchronous also(not executed by JS engine).A beginner of JS would code it using callbacks, it is not wrong , but it becomes hell when it keeps digging further and further.

a glimpse of callback hell

This hell is solved by promises.

We can create our own promise using a promise constructor that receives a callback.

promise using promise constructor

A promise object has [[PromiseState]] and [[ promiseResult]].

[[PromiseStatus]] can be “pending”, ”fullfilled”/”resolved”, “rejected”.

Why does that status matter ? => Because, using that we know whether the task is still being performed, finished successfully or there was some issue. Actually the callback in promise receives 2 arguments also , resolve and reject.

resolve is called when promise should resolve or get fulfilled. wheras reject is called if something has gone wrong.

resolve and reject arguments in callback

for getImage to return a Promise, something like below image can be done. There are some built in functions also, which by default return promise only and some we create like below

method to create a fn that returns a Promise
how data resolved/error from promise object is handled

To a promise object three methods are attached :-

.then() : gets called when a promise is resolved.It has a callback that has an argument and that argument only holds the resolved data (i.e what we desire).

.catch() : gets called when a promise is rejected. It has a callback that has an argument and that argument holds the rejected message of error(i.e reject(new Error(error)) from that getImage fn)

.finally() : this always gets called and is independent of rejection or resolved

Having discussed all this , lets now solve our callback hell problem using Promises :D

solving callback hell problem using Promise

BONUS !!!!

We all know about callback queue/macrotask queue as already discussed in Event loop.

Now lets get introduced to something called as microtask queue and this queue has to do something with the promise.

Like callbacks of setTimeout,setInterval,setImmediate are pushed to callback queue/macrotask queue .Similarly callbacks of Promise’s .then(), .catch(), .finally() are pushed to microtask queue.

And the most important point :- after JS call stack gets empty, event loop looks into microtask queue first,executes it and after microtask queue is empty , it goes to macrotask queue and repeats the same.

For detailed info refer :- deep dive into task quesus, js stack, schedules

More stuff coming in Day 2 of T20 JS , stay tuned :P

stay tuned!!

--

--