Discover structuredClone(), array.at(), and the Change Array by Copy Proposal

Scofield Idehen - Jun 12 '23 - - Dev Community

JavaScript, as a dynamic and constantly evolving language, continues to introduce new features that enhance developers' productivity and expand the capabilities of the language.


JavaScript developers must stay up-to-date with these advancements. In this article, we will explore three exciting features: structuredClone(), array.at(), and the Change Array by Copy Proposal, which has recently reached the finished stage (4).

Background: The Evolution of ECMAScript and the TC39 Process

The evolution of the ECMAScript (JavaScript) standard is guided by the efforts of ECMA TC39, a governing body comprising volunteers from various companies and organizations.

TC39 follows a rigorous process to introduce new language features. Proposals undergo thorough discussions and evaluations, progressing through multiple stages.

Once a proposal reaches stage 4, it achieves completion and official standardization.

These finalized features are published on TC39's GitHub repository, ensuring transparency and accessibility for developers worldwide.

While the structuredClone() method was introduced in ECMAScript 2015 and the array.at() method in ECMAScript 2022, some developers may still be unaware of these powerful features. Hence, let's explore them together, with the aim of empowering all JavaScript developers.

Moreover, the upcoming 2023 edition of ECMAScript holds even more promises, including the introduction of array.with() and other methods from the transformative 'Change Array by Copy' proposal, along with other exhilarating new features and notable improvements.

structuredClone()

Introduced in ECMAScript 2015 (ES6), the structuredClone() method provides a convenient way to clone JavaScript objects.

This method enables the creation of a deep copy of an object, including its properties and methods, without any shared references to the original object's properties or values.

It proves particularly useful when dealing with complex data types like arrays, objects, Maps, and Sets or when cloning non-serializable objects such as DOM elements, IndexedDB objects, and other intricate data structures.

Say goodbye to deep cloning using non-native methods like JSON.parse(JSON.stringify(object)) or Lodash cloneDeep()!

Here's an example of using structuredClone():


// With an object:
const originalObject = {
  name: 'John Doe',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'Anytown',
    state: 'CA'
  },
  hobbies: ['reading', 'traveling', 'photography']
};

const clonedObject = structuredClone(originalObject);

// With an array:
const mushrooms1 = {
  amanita: ["muscaria", "virosa"],
};

const mushrooms2 = structuredClone(mushrooms1);

mushrooms2.amanita.push("pantherina");
mushrooms1.amanita.pop();

console.log(mushrooms2.amanita); // ["muscaria", "virosa", "pantherina"]
console.log(mushrooms1.amanita); // ["muscaria"]

Browser Support

The structuredClone() method is available in Node.js v16.8.0 and above. It is also supported by Firefox, Chrome, Edge, and Safari browsers. However, it is not available in Internet Explorer or Opera Mini.

array.at():

The array.at() method was added to JavaScript in ECMAScript 2022, becoming available for Array, String, and TypedArray objects. This method addresses a long-standing user request, making accessing array elements and handling edge cases easier.

array.at() takes an integer argument, allowing you to access an element in an array at a specific index. Unlike the bracket notation [length-1], which treats values inside square brackets as string properties, array.at() provides a more convenient and intuitive way to access array elements, including support for negative index values.

It returns undefined if the index is out of the array bounds, without attempting to access the corresponding property.

Let's take a look at an example:

// Our array:

const colors = ["red", "green", "blue"];


// Using length property

const lengthWay = colors[colors.length - 2];

console.log(lengthWay); // 'green'


// Using slice() method. Note that an array is returned

const sliceWay = colors.slice(-2, -1);

console.log(sliceWay[0]); // 'green'


// Using at() method

const atWay = colors.at(-2);

console.log(atWay); // 'green'

Browser Support

The array.at() method is available in Node.js v15.0.0 and above and browsers such as Firefox, Chrome, Edge, and Safari. However, it is not available in Internet Explorer or Opera Mini.

Change Array by Copy Proposal: Revolutionizing Array Manipulation

The Change Array by Copy Proposal is currently under consideration by the TC39 committee. It aims to enhance JavaScript arrays by introducing several methods that allow modifying arrays by returning copies, leaving the original array untouched. These proposed methods include:

  1. Array.prototype.toReversed(): Returns a reversed copy of the array.
  2. Array.prototype.toSorted(compareFn)(): Returns a sorted copy of the array using the specified comparison function.
  3. Array.prototype.toSpliced(start, deleteCount, ...items)(): Returns a copy of the array with elements spliced in or out based on the specified parameters.
  4. Array.prototype.with(index, value)(): Returns a copy of the array with the element at the given index replaced with the specified value.

These methods offer a convenient and intuitive way to perform array operations without directly modifying the original array.

This approach allows for more declarative and chainable array operations while preserving data integrity. Although the Change Array by Copy Proposal is still in the proposal stage, it can be a game-changer for developers who regularly work with arrays.

Let's see an example demonstrating the usage of the proposed methods:

const arr = [3, 1, 4, 2, 5];
const reversed = arr.toReversed();
console.log(reversed);  // Output: [5, 2, 4, 1, 3]
const sorted = arr.toSorted();
console.log(sorted);    // Output: [1, 2, 3, 4, 5]
const spliced = arr.toSpliced(1, 2, 'a', 'b');
console.log(spliced);   // Output: [3, 'a', 'b', 5]
const updated = arr.with(2, 'c');
console.log(updated);   // Output: [3, 1, 'c', 2, 5]

Browser Support

Chrome/V8: The methods are available in Chrome browsers without additional configuration or flags, starting from Chrome 110.

Safari/JavaScriptCore: The methods have been available since Safari Tech Preview 146.

Ladybird/LibJS: The methods are available.

Firefox/SpiderMonkey: The methods are currently flagged.

Conclusion

JavaScript continues to evolve with new features and updates, making it an incredibly powerful programming language.

This article explored some exciting JavaScript features: structuredClone(), array.at(), array.toReversed(), array.toSorted(), array.toSpliced(), and array.with().

If you find this post exciting, find more exciting posts like this on Learnhub Blog; we write everything tech from Cloud computing to Frontend Dev, Cybersecurity, AI and Blockchain.

Resource

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player