How does JavaScript handle concurrent access to variables?

I am developing a Chrome extension that utilizes asynchronous functions. In this context, I have a global string variable that is modified by a function like this: mySharedString += additionalText. I’m curious about the potential risk involved if I attempt to read mySharedString within a different function simultaneously. Specifically, could I end up retrieving only part of additionalText? In essence, is the concatenation operation—or more broadly, any operation—considered atomic in this scenario?

JavaScript executes code in a single-threaded manner through an event loop, which means that operations are generally atomic at a high level; however, this does not eliminate the risks associated with concurrency when utilizing asynchronous functions. Your concern about reading mySharedString while it is being modified is valid but requires a bit more context.

When mySharedString += additionalText is executed, JavaScript handles the operation as an atomic, single-step operation in terms of the event loop, meaning no other operations will intervene in between. Therefore, you wouldn't typically retrieve only part of additionalText during a read. However, simultaneous reads and writes are not inherently protected or synchronized, which could still lead to unexpected results in some asynchronous scenarios.

To illustrate, if one asynchronous function begins modifying mySharedString while another reads it, the usual expectation is that the read would occur either before or after the string modification, not during. However, to ensure consistency and avoid race conditions, consider using a mutex-like mechanism or a flag to coordinate access.

let lock = false;

async function updateSharedString(additionalText) {
  while (lock) await new Promise(resolve => setTimeout(resolve, 10));
  lock = true;
  try {
    mySharedString += additionalText;
  } finally {
    lock = false;
  }
}

In this example, the async update function simulates a lock, yielding control and waiting if mySharedString is already being modified. Though JavaScript's single-threaded nature minimizes the overlap in practical terms, good practices involve safeguarding against potential concurrency issues, particularly in more complex or resource-constrained environments like Chrome extensions.