DEV Community

Jeremy Panjaitan
Jeremy Panjaitan

Posted on

# Asynchronous vs Synchronous in javascript

synchronous and asynchronous are very confusing concepts in javascript programming language especially for the beginners. for me it will took very long time to understand those two concepts. in this article i will share with you the difference between asynchronous and synchronous in javascript. is it one better than the other ?

what is synchronous ?

synchronous means that if you execute some code, it will be executed the code line by line. javascript uses single threaded and also uses synchronous execution model. single thread means that one statement is being executed at a time. so in javascript one thing is happening at a time. take a look of this code

console.log("first statement")
console.log("second statement")
console.log("third statement")
Enter fullscreen mode Exit fullscreen mode

The result will be :

first statement 
second statement 
third statement
Enter fullscreen mode Exit fullscreen mode

as we can see, the statement was executed line by line.

what is asynchronous ?

asynchronous is the opposite of synchronous. Each statement will not wait for the previous statement to finish before executing the next statement. there are many examples of asynchronous such as promises, async/await, setTimeout function, and setInterval function. but in this article i will stick to the basic example. just for the basic understanding. consider these lines of code

setTimeout(function () { console.log("foo") }, 4000)
console.log("bar")
Enter fullscreen mode Exit fullscreen mode

guess which console.log will be executed first...

bar
//wait for 4 seconds
foo
Enter fullscreen mode Exit fullscreen mode

as you can see the second statement was executed first. in this example setTimeout is non-blocking, because it didn't block the execution of the second statement.

now, which one is better ? does one of them is better compare to the other ?

actually there is none of them is better compare to the other. each of them suited for specific use cases. generally in web development asynchronous is used when making a request to the api, when doing a task that will be finished later. synchronous is used when we need to execute the code sequently

that's all for this article. thank you for reading to my first article. leave a comment if i have wrong understanding about this concept. thank you

Top comments (0)