What is the use of Atomics.store() method in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Atomics.store()

Atomics.store() is an inbuilt method that is used to store a specific value at a specific position in an array. This method accepts an Integer typed array, index and the value as arguments.

Syntax

Atomics.store(typedArray, index, value);

Parameters

  • typed array - it the shared integer typed array that we need to modify.
  • index - It is the position in the array where we are going to store the value.
  • value - it is number we want to store.

Whenever we want to store a value at a specific place and wants to return the stored value then Atomics.store() is used.

One should note that Atomics are used with SharedArrayBuffer(generic fixed-length binary data buffer) objects. They cant be used with a new operator or can't be invoked as a function.

Example

In the following example initially SharedArrayBuffer object is created. Then an array 'arr' is taken and assigned a value '7' initially at index 1. later on using Atomics.store() the value 7 at index 1 is replaced with value 3 and the updated value is returned. For confirmation whether the new value is stored or not, Atomics.load() method, which will give the final updated array, is used and the updated value is displayed in the output.

Live Demo

<html>
<body>
<script>
   var buf = new SharedArrayBuffer(25);
   var arr = new Uint8Array(buf);
   arr[1] = 7;
   var res = Atomics.store(arr, 1, 3)
   document.write(res);
   document.write("</br>");
   document.write(Atomics.load(arr,1));
</script>
</body>
</html>

Output

3
3
raja
Published on 26-Jun-2019 18:38:05
Advertisements