First i strongly recommend you to read my following blog 👇
It covers all the basic terminologies with beautiful explanation which i am using in this blog.
Lately when i studied about the architecture of Node.js and how beautifully it handles JavaScript internally i got amazed.
And there i got to know about the behavior of Synchronous & Asynchronous JavaScript
In this blog we will cover :-
- What synchronous code means
- What asynchronous code means
- Why JavaScript needs asynchronous behavior
JavaScript is Synchronous
By default JavaScript is synchronous single threaded language.
Means code executes from top to bottom , left to right sequentially and wait until one code gets finished.
function f1() {
// Some code
}
function f2() {
f1();
}
function f3() {
f2();
}
f3();
Underthehood it will create a stack (Data-Structure in JavaScript) also known as call Stack which keeps the record of function.
If the function call another function then engine adds the second function to the stack and start executing it until it finishes and then takes it out from the stack.
credits :- https://www.freecodecamp.org/news/synchronous-vs-asynchronous-in-javascript/
Hope you understand it now how JavaScript handles synchronous code
Asynchronous JavaScript
An Asynchronous code runs in background without stopping your main code.
Unlike synchronous code it doesn't block your main thread So your code can execute without waiting another code to finish
setTimeout(() => console.log("Like and share") , 1000)
console.log("Already liked this blog !!!")
In the above example what we do is simply make a Asynchronous function that will execute after 1sec it will not block the block main thread to execute my another console log
But why do we need asynchronous behavior lets see
Why JavaScript needs asynchronous behavior
JavaScript needs asynchronous behavior as it is single threaded it can do only one thing at a time
If everything were synchronous:
Handling database took soo much time that you can't imagine
Also API calls , file read , timers would block the main thread
If you want to know more about asynchronous behavior check this blog 👇
I have covered all the examples there using asynchronous callbacks
Thanks for reading ! if enjoyed this blog , you can read more on this 👇
This article was originally published by DEV Community and written by Kunal .
Read original article on DEV Community
