DEV Community

Akash
Akash

Posted on

Java script is Single_Threaded

  • JavaScript is a single-Threaded language why because it execute only one code at a time no parallel execution by default
  • Without finish or executing a code it never moves to another

=> Justify why JS is Single Threaded

  • To keep the language simple and efficient JavaScript was made single threaded
  • Demerit of single threaded is long running task can block the execution of other code,other script pages will not run until it completes it execution
  • Whereas JS is single threaded and synchronous the browser environment or node.js makes it to behave like asynchronous
  • Only ( Browser or node .js ) make js to behave like Multi-threaded and asynchronous
  • Thats why we writing non blocking code and also asynchronous code even though JS runs in one thread.
  • If the main loop is blocked no other code is executed it blocks code being executed.

=> Let Clarify the Synchronous and Asynchronous

1. Synchronous

  • Code runs line by line ,each line waits for another line to execute code

(e.g) Imagine biriyani is being cooked without rice we can't move for another process,without chicken we can't move to preparing biriyani .once each and every things is ready then it comes under odred in process of making.

2. Asynchronous

  • In this case code does not wait for one line to get execute ,it moves and come back when it done ,which means easy code runs quicker it comes first and complicated code will take time to execute after executing it comes under process.

(e.g) In hotel whose order is simple and easy to make will serve first and whose bit more take time to be done will get later

  • JS is naturally synchronous single threaded and synchronous but (Browser and Node.js) makes it to behave like asynchronous.
  • For solving Asynchronous difficulties JS has callback function,promises, Async

    • In callback function once the code is ready callback used to executing the code.

:- Above content refered in LinkedIn,reddit.

Top comments (0)