Exploring New JavaScript Features: Practical Examples - 2023 |

Exploring New JavaScript Features: Practical Examples - 2023

Posted on Sep 3, 2023

JavaScript is an ever-evolving language, continuously being updated with new methods and features to enhance its capabilities. Today, we’ll delve into some of the latest additions to the JavaScript repertoire. We’ll provide practical examples for each to give you a hands-on feel of how they operate.

1. Array.prototype.toSorted

This is an effortless way to sort arrays. Check out the example below:

let arr = [5,4,2,3,1];
console.log(arr.toSorted()); // [1, 2, 3, 4, 5]

2. Array.prototype.toReversed

Reversing arrays is now simpler:

let arr = ["a", "b", "c", "d", "e"];
console.log(arr.toReversed()); // ['e', 'd', 'c', 'b', 'a']

3. Array.prototype.with

This is an intriguing method that lets you replace an element at a specific index:

const arr = ["I", "am", "the", "Walrus"];
const newArr = arr.with(3, "Ape Man");
console.log(newArr); // ["I", "am", "the", "Ape Man"]

4. Array.prototype.findLast

Seeking the last item in an array that matches a criterion? This method has you covered:

const numbers = [54, 34, 55, 75, 98, 77];
const lastEvenNumber = numbers.findLast(element => element % 2 === 0);
console.log(lastEvenNumber); // 98

5. Array.prototype.findLastIndex

Like the previous method, but returns the index of the last element that meets your condition:

const numbers = [54, 34, 55, 75, 98, 77];
const lastEvenIndex = numbers.findLastIndex(x => x % 6 === 0);
console.log(lastEvenIndex); // 0 (index of 54)

6. Array.prototype.toSpliced

Splice and get a new array without modifying the original:

const colors = ["red", "orange", "yellow", "green", "blue", "purple"];
const newArr = colors.toSpliced(2, 1, "pink", "cyan");
console.log(newArr); // ["red", "orange", "pink", "cyan", "green", "blue", "purple"]

7. Official Shebang Support

No more rigmaroles! Run your JavaScript file directly from the command line (provided you have Node.js installed):

#!/usr/bin/env node
console.log("Hello, world!");

Command:

chmod +x hello.js
./hello.js

8. Symbols as Keys on Weak Collections

A more advanced feature, symbols can now act as keys for weak collections:

var map = new WeakMap();
let mySymbol = Symbol("FooBar");
map.set(mySymbol, "Some Value");
console.log(map.get(mySymbol)); // "Some Value"