In my JavaScript code, I have a line of code that looks like this:
const newArray = oldArray.splice(0);
My question is what happens when there are concurrent modifications to oldArray
during the execution of this line. Specifically:
oldArray
while splice(0) is executing, will those new elements be included in the newArray
?oldArray
be emptied, or will it still contain the elements that were added during the execution of splice(0)?And compare to the following way:
const newArray = oldArray.slice();
oldArray = oldArray.slice(newArray.length);
Which way is better?
My goal is if the new element added to the oldArray
, I want to keep them in the oldArray
, I don't want to loss any data.
I want to make sure I understand the behaviour correctly and handle potential concurrency issues. Thank you for your help!
I don't know how to verify my thought.
since javascript is single-threaded, it is very unlikely that there will be 2 operations on the array at the same time. So I don't see any difference between the two approaches you mentioned. Nevertheless, the variant with
const newArray = oldArray.slice();
oldArray = oldArray.slice(newArray.length);
sounds better to me, since you determine the behavior yourself.
For more information about the differences between splice and slice have a look here ;)