1.

substr() vs substring() in JavaScript?

Answer»

JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time. 

Many PEOPLE think JavaScript is asynchronous because we can do async tasks like SETTIMEOUT, CALLBACKS, promises in it. But the asynchronous behaviour of JavaScript(setTimeout, callbacks, promises) is not a part of JavaScript itself and built on top of JavaScript language in browser and accessed through browser APIs.

The browser have a Call Stack, Browser API and Message Queue and the ORDER of their processing is called event loop.

We will see the working of the classic interview question to understand how the event loop and with it the asynchronous behaviour of JavaScript works.

function main() {   console.log('A');   setTimeout(function(){     console.log('B');   },0);   console.log('C');   } main();  

//Output

//A //C //B

The output will be A C B , even after the setTimeout() was set to display “b” after 0 ms. This happens because of the internal working of the browser. Let’s look into the step of execution.

The main() is pushed into Call Stack, which then console logs A. Then it is popped out and the setTimeout is pushed into Call Stack. Now the setTimeout() uses Browser API, so it is pushed there and the console log C is pushed into Call Stack.

  • Even with the delay of 0ms the exec() for setTimeout have to go to the Message Queue.
  • After all the statements of main() is RUN and the Call Stack is empty, then only the exec() from Message Queue can be pushed to the Call Stack.

This is how event loop works and the asynchronous, non-blocking part of JavaScript comes from.



Discussion

No Comment Found