JavaScript is Synchronous and Single Threaded. (Unfolding the Async Behaviour)

Guess what’s synchronous. JAVASCRIPT!

var data = fetchData();console.log(data);

What is meant by asynchronous and synchronous.

console.log(1);console.log(2);console.log(3);console.log(4);console.log(5);output:// 1 2 3 4 5
function asyncConsole(time,value){setTimeout(function(){console.log(value);},time);}asyncConsole(200,1);asyncConsole(100,2);asyncConsole(400,3);asyncConsole(500,4);asyncConsole(300,5);output:// 2 1 5 3 4

The Event Loop

console.log(“1”);for(){// a loop that takes 5 seconds to complete}console.log(“2”);
console.log(“1”);setTimeout(function(){},5000)console.log(“2”);

How to understand order of execution of any code in JavaScript.

function blockThreadFor(numberMillis) { 
var now = new Date();
var exitTime = now.getTime() + numberMillis;
while (true) {
now = new Date();
if (now.getTime() > exitTime)
return;
}
}
function printData(data){
console.log(data.title)
};
function printHello(){
console.log("Hello");
}
setTimeout(printHello,0);let futureData = fetch("https://jsonplaceholder.typicode.com/todos/1"); // take 100 ms to return datafutureData.then((response)=>{
return response.json();
}).then(printData)
blockThreadFor(1500);console.log("Hi");
Hidelectus aut autemHello

Fullstack developer. React ● Node ● Go ● Elixir. I make awesome stuff with my bare hands 👐🏻

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store