0

I'm using Nodejs, and I'm confused about the asynchronous characteristics of JavaScript.

If there are no callback functions or promises, is every function executed in asynchronous way?

For example,

let arr = []
for (let i = 0; i < 600; i++) {
    arr.push(i)
}
console.log(arr)
arr = []
console.log(arr)

What if arr becomes an empty array while arr is being pushed by the 'for' statement?

I executed above code several times, and fortunately, there were no worring situation. Is that a coincidence?


Here is another example:

function foo(num) {
    console.log(num)
}
let a = 0
foo(a)
a = 1

I want to make foo(a) in the above code always returns 0, not 1.

What if Node.js runtime executes a=1 earlier than foo(a)?

Should I add promise in these trivial cases?

JMP
  • 4,417
  • 17
  • 30
  • 41
  • `I want to make foo(a) in the above code always returns 0,` - your function code doesn't return anything. To return something, you need to have a `return` statement (e.g., return _something_;). – prasad_ Apr 28 '23 at 07:22

1 Answers1

1

If there are no callback functions or promises, is every function executed in asynchronous way?

In general, JavaScript is executed synchronously.

Some functions are asynchronous. They generally return a promise or accept a callback so that people calling them can do something when they are complete.

What if arr becomes an empty array while arr is being pushed by the 'for' statement?

In your example, that cannot happen. The code you wrote is synchronous.

If some asynchronous code was running, then it wouldn’t be on the same event loop and would not have access to that variable. If said asynchronous code triggered a callback then it would be queued until that event loop was free.

What if Node.js runtime executes a=1 earlier than foo(a)?

It won’t. JavaScript does not randomise the order of statements.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335