Menu

1 / 2

Synchronous ,Asynchronous , Promise in JS

DEV Community·Nanthini Ammu·6 months ago
#AQBZDMLf
Reading 0:00
15s threshold

Synchronous JavaScript :

Code runs line by line, and each line waits for the previous one to finish.

console . log ( " First " ); console . log ( " Second " ); console . log ( " Third " );

Output : First Second Third

Enter fullscreen mode

Exit fullscreen mode

If a single line of code takes a long time (like a huge loop or a complex calculation), it blocks the rest of the program from running.

function slowTask (){ for ( let i = 1 ; i < 999999999 ; i ++ ){

} } console . log ( " First " ); slowTask (); console . log ( " Third " );

Output : First Third

Enter fullscreen mode

Exit fullscreen mode

Asynchronous JavaScript :

Asynchronous code allows a program to start a long-running task and continue with others before that task finishes.

Code doesn't wait — it moves on and comes back when the task is done.So the page wouldn't freeze.

Used in:

Fetching data from an API.

Reading a file

Database queries

Timers

console . log ( " First " ); setTimeout (() => { console .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.