0

Will the following codes behaves different in asynchronous scenario?

a.unshift(x)

a = [x].concat(a)

How do I verify that?

Since unshift operates on the array directly, while the assignment = will create a new array.

So I am wondering if they are running among massive code and there are asynchronous function that invoking them, will they behaves differently?

Will it happen to lose something when using .concat?

Example:

let a = []
a = ['a'].concat(a)
a = ['b'].concat(a)
a = ['c'].concat(a)

// a = ['c', 'b', 'a']

Normally the above code are equivalent to the followings:

let a = []
a = a.unshift('a')
a = a.unshift('b')
a = a.unshift('c')

// a = ['c', 'b', 'a']

But will the later one be more secure? What if in some rare cases, while the a = [x].concat(a) is still in progress, the other places changed the a, and after the a = [x].concat(a) completes, the previous change would be lost.

Will this happen?

Jeff Tian
  • 5,210
  • 3
  • 51
  • 71
  • 1
    None of those functions are asynchronous. What do you mean by "asynchronous scenario"? – CertainPerformance Dec 13 '19 at 07:54
  • They are invoked by some asynchronous functions. – Jeff Tian Dec 13 '19 at 07:58
  • 1
    You will get a different behaviour than expected if you have something like `arr.concat(await somePromise)` and that line is executed multiple times. If you use `arr.unshift(await somePromise)` then you would be fine. However, this can easily be amended by having `await` and the addition on different lines `let value = await somePromise; arr = arr.concat(value)` will perform as expected. – VLAZ Dec 13 '19 at 08:18
  • You can see an example [of `arr.concat(await somePromise)` playing badly with asynchronicity here](https://stackoverflow.com/questions/58612969/different-behavior-of-async-functions-when-assigning-temporary-to-variable/) – VLAZ Dec 13 '19 at 08:20
  • 1
    Conceptually & actually, javascript is a single-threaded language. It won't suffer that abrupt thread shift you'll see in languages like C/C++. The ambiguity you're eluding to only occurs in the deferred processing of code blocks marked as asynchronous -- e.g., await & promises. So if you had `await unshift` for example, you may see the disorder. – bvj Dec 13 '19 at 08:23

0 Answers0