Why are functions synchronous in Javascript?

Javascript has asynchronous operations. But, a for loop is synchronous, not asynchronous. The code you show doesn’t use any asynchronous operations, therefore it’s all synchronous.

Should myfunc() execute in node and take longer, so that “end” should be invoked earlier because javascript is asynchronous?

No. Nothing in myfunc() is asynchronous. That’s all synchronous code in your question.

Operations such as setTimeout() or http.get() or fs.readFile() are all asynchronous operations. They don’t change the fact that the for loop runs synchronously, but the responses to any asynchronous you might put in the loop will happen AFTER your console.log("end") runs.

If you did something like this:


function myfunc(){
  for(let i=0; i<10; i++){
      setTimeout(function() {
          console.log(`timer ${i} done now`);
      }, 100);
  console.log("this should be the end")

Would then show this output:

this should be the end
timer 0 done now
timer 1 done now
timer 2 done now

This is the sequence of operations:

  1. output console.log("start")
  2. call myfunc()
  3. run the for loop starting 10 setTimeout() asynchronous operations
  4. finish the for loop and output console.log("this should be the end")
  5. myfunc() returns
  6. Output console.log("end")
  7. Some time later the first timer finishes and calls its callback and outputs timer 0 done now.
  8. The rest of the timers finish
  9. The for loop runs synchronously and starts all the timers and then myfunc() returns.

Leave a Comment