Ask HN: Does JavaScript have race conditions?

2 points by namelezz ↗ HN
During an interview, I was asked how to avoid race conditions in JavaScript. When I explained why JS did not have race conditions(single threaded event loop) the interviewer looked unhappy. I googled and received mixed answers. Some say yes while others say no. Any experts here can help me with this confusion?

3 comments

[ 3.4 ms ] story [ 19.0 ms ] thread
Yes, (in my view) you can have race conditions any time asychronous operations (like network requests) finishing in different orders results in unexpected state. You don't get the specific type of race condition caused by interleaved multi-threaded code though. So it depends on how restrictive your definition of a race condition is. (Those races belong to the system as a whole, so are arguably not "in JavaScript.")

But since that's possible in basically all languages, I think your answer is more responsive to a question about race conditions and JavaScript. If the interviewer didn't like it, he/she could have dug into the issue more.

I think he wanted you to make use of Promises.
Javascript as a language is single threaded. Essentially JS is just an API working with text,arrays, dates but does not include I/O (networking and storage) typically implemented by host environment.(mostly browsers). So this is where async nature arises from the network requests and storing data. Hence race conditions can arise from doing async operations on which finishes first.