Discover structuredClone(), array.at(), and the Change Array by Copy Proposal
Tags: webdev, javascript, beginners, programming
Published: 2023-06-12 03:03:13


JavaScript, as a dynamic and constantly evolving language, continues to introduce new features that enhance developers' productivity and expand the capabilities of the language.</p>
JavaScript developers must stay up-to-date with these advancements. In this article, we will explore three exciting features: structuredClone(), <a href="http://array.at" target="_blank" rel="noopener noreferrer nofollow">array.at</a>(), 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 <a href="http://array.at" target="_blank" rel="noopener noreferrer nofollow">array.at</a>() 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.
<h2>structuredClone()</h2>
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():
<pre><code class="language-javascript">
// 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"]</code></pre>
<h2>Browser Support</h2>
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.
<h2><a href="http://array.at" target="_blank" rel="noopener noreferrer nofollow">array.at</a>():</h2>
The <a href="http://array.at" target="_blank" rel="noopener noreferrer nofollow">array.at</a>() 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.

<a href="http://array.at" target="_blank" rel="noopener noreferrer nofollow">array.at</a>() 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, <a href="http://array.at" target="_blank" rel="noopener noreferrer nofollow">array.at</a>() 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:
<pre><code class="language-javascript">// 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'</code></pre>
<h2>Browser Support</h2>
The <a href="http://array.at" target="_blank" rel="noopener noreferrer nofollow">array.at</a>() 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.
<h2>Change Array by Copy Proposal: Revolutionizing Array Manipulation</h2>
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:
<ol>
 	<li>Array.prototype.toReversed(): Returns a reversed copy of the array.</li>
 	<li>Array.prototype.toSorted(compareFn)(): Returns a sorted copy of the array using the specified comparison function.</li>
 	<li>Array.prototype.toSpliced(start, deleteCount, ...items)(): Returns a copy of the array with elements spliced in or out based on the specified parameters.</li>
 	<li>Array.prototype.with(index, value)(): Returns a copy of the array with the element at the given index replaced with the specified value.</li>
</ol>
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:
<pre><code class="language-javascript">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]</code></pre>
<h2>Browser Support</h2>
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.
<h2>Conclusion</h2>
JavaScript continues to evolve with new features and updates, making it an incredibly powerful programming language.

This article explored some exciting JavaScript features: structuredClone(), <a href="http://array.at" target="_blank" rel="noopener noreferrer nofollow">array.at</a>(), array.toReversed(), array.toSorted(), array.toSpliced(), and array.with().

If you find this post exciting, find more exciting posts like this on <a class="attrlink" href="http://blog.learnhub.africa/" target="_blank" rel="noopener noreferrer nofollow">Learnhub Blog</a>; we write everything tech from <a class="attrlink" href="https://blog.learnhub.africa/category/cloud-computing/" target="_blank" rel="noopener noreferrer nofollow">Cloud computing</a> to <a class="attrlink" href="https://blog.learnhub.africa/category/frontend/" target="_blank" rel="noopener noreferrer nofollow">Frontend Dev</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/security/" target="_blank" rel="noopener noreferrer nofollow">Cybersecurity</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/data-science/" target="_blank" rel="noopener noreferrer nofollow">AI</a> and <a class="attrlink" href="https://blog.learnhub.africa/category/blockchain/" target="_blank" rel="noopener noreferrer nofollow">Blockchain</a>.
<h2>Resource</h2>
<ul>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/05/24/mastering-javascript-array-and-its-methods/" target="_blank" rel="noopener noreferrer nofollow">Mastering JavaScript Array and its Methods</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/05/09/20-best-javascript-frameworks-for-2023/" target="_blank" rel="noopener noreferrer nofollow">20 Best JavaScript Frameworks For 2023</a></li>
</ul>