CodeNewbie Community

loading...

What is the difference between synchronous and asynchronous?

willthethrill profile image Will ・1 min read

Hello friends! As I start my JavaScript journey, I keep hearing that JS is an asynchronous language. Can anyone help me understand what the difference between synchronous and asynchronous languages is?

Much appreciated folks!

Discussion (2)

Collapse
ben profile image
Ben Halpern

"Synchronous" means that one thing happens after another. It's probably the simplest way to program. The events of line 11 will always happen after line 10.

"Asynchronous" means that the events of line 11 might begin before the events of line 10 complete. JavaScript is generally synchronous, but allows for asynchronous functionality. Things like fetching the results of a web request are often done asynchronously— And for good reason. If you need to fetch data from a URL, it is not very efficient to wait around doing nothing while the request is sent and returned. Where possible, it's good if other code can execute. For example, I may also want to respond to a separate click event while I wait.

All in all, reconciling async code can be complicated. JavaScript has several ways to accomplish sane async programming. Check out this explanation of promises and async/await for more info.

Collapse
gaurang847 profile image
Gaurang • Edited

I'll give an example.

If JavaScript were synchronous, it would've printed 42 to the console (considering the call was successful).
Since it is asynchronous, it calls the get_value_from_DB method but it does not wait till it finishes.
It knows that DB operations rely on network and I/O; which are slow. And hence, it lets the execution of your program move ahead before get_value_from_DB could return a value.
Hence, it prints undefined.

The benefit of this is, that JavaScript is fast. It does not have to wait for slow operations to complete. (Although it might be possible to force JavaScript to do that at times. That's considered a bad practice though).
The disadvantage is that you have to learn how to complete your tasks despite this async behavior.
For example, how do I write the result (be it 42 or -1) of get_value_from_DB to the console?

Forem Open with the Forem app