Enhance Your Code: The Latest and Greatest JavaScript Methods
Published: 2024-06-08 08:26:08

Here are some of the latest and most useful JavaScript methods that have been introduced in recent versions of ECMAScript (ES2020, ES2021, ES2022, and ES2023):

### 1. **`String.prototype.replaceAll()`**
Replaces all occurrences of a substring in a string.

```javascript
const str = 'foo bar foo';
const newStr = str.replaceAll('foo', 'baz');
console.log(newStr); // baz bar baz
```

### 2. **`Promise.allSettled()`**
Returns a promise that resolves after all of the given promises have either resolved or rejected.

```javascript
const promises = [
    Promise.resolve(1),
    Promise.reject('error'),
    Promise.resolve(3)
];

Promise.allSettled(promises).then((results) => {
    results.forEach((result) => console.log(result.status));
});
// fulfilled
// rejected
// fulfilled
```

### 3. **`Logical Assignment Operators`**
Combines logical operations with assignment.

```javascript
let a = 1;
a ||= 2; // a = a || 2
console.log(a); // 1

let b = 0;
b &&= 2; // b = b && 2
console.log(b); // 0

let c = null;
c ??= 3; // c = c ?? 3
console.log(c); // 3
```

### 4. **`Nullish Coalescing Operator (??)`**
Provides a default value when the left-hand side is `null` or `undefined`.

```javascript
const foo = null ?? 'default value';
console.log(foo); // default value
```

### 5. **`Optional Chaining (?.)`**
Allows safe access to deeply nested properties.

```javascript
const user = { address: { street: 'Main St' } };
const street = user?.address?.street;
console.log(street); // Main St
```

### 6. **`BigInt`**
A built-in object that provides a way to represent whole numbers larger than `2^53 - 1`.

```javascript
const largeNumber = BigInt(123456789012345678901234567890);
console.log(largeNumber); // 123456789012345678901234567890n
```

### 7. **`WeakRef` and `FinalizationRegistry`**
Allows creation of weak references to objects and registers a cleanup callback for when the object is garbage collected.

```javascript
let target = { data: 'some data' };
const weakRef = new WeakRef(target);

const registry = new FinalizationRegistry((heldValue) => {
    console.log(`Cleaned up ${heldValue}`);
});

registry.register(target, 'some data');
target = null;
// Later, when garbage collected, "Cleaned up some data" will be logged.
```

### 8. **`Array.prototype.at()`**
Allows relative indexing in arrays.

```javascript
const array = [10, 20, 30, 40];
console.log(array.at(-1)); // 40
```

### 9. **`Object.hasOwn()`**
A safer alternative to `Object.prototype.hasOwnProperty`.

```javascript
const obj = { key: 'value' };
console.log(Object.hasOwn(obj, 'key')); // true
```

### 10. **`Top-level await`**
Allows using `await` at the top level of modules.

```javascript
// In a module file (e.g., module.mjs)
const data = await fetchData();
console.log(data);
```

### 11. **`Relative indexing method for Strings`**
The `at()` method is also available for strings.

```javascript
const str = 'hello';
console.log(str.at(-1)); // 'o'
```

### 12. **`Object.fromEntries()`**
Transforms a list of key-value pairs into an object.

```javascript
const entries = new Map([
    ['foo', 'bar'],
    ['baz', 42]
]);

const obj = Object.fromEntries(entries);
console.log(obj); // { foo: 'bar', baz: 42 }
```

These methods and operators provide more flexibility and efficiency in handling common programming tasks.