ECMAScript some features you might find useful
Himanshu Gupta
Posted on May 11, 2023
- String.prototype.replaceAll() method:
const str = 'This is a test string.';
const newStr = str.replaceAll('is', 'was');
console.log(newStr); // Output: 'Thwas was a test string.'
- Array.prototype.at() method:
const arr = [1, 2, 3, 4];
console.log(arr.at(2)); // Output: 3
- Promise.any() method:
const promise1 = new Promise((resolve) => setTimeout(resolve, 1000, 'first'));
const promise2 = new Promise((resolve) => setTimeout(resolve, 2000, 'second'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 3000, 'third'));
Promise.any([promise1, promise2, promise3])
.then((value) => console.log(value)); // Output: 'first'
- Numeric separators:
const billion = 1_000_000_000;
console.log(billion); // Output: 1000000000
- Logical assignment operators:
let a = 1;
a &&= 2;
console.log(a); // Output: 2
let b = 0;
b ||= 3;
console.log(b); // Output: 3
let c;
c ??= 4;
console.log(c); // Output: 4
- replace All
console.log('10101010'.replaceAll('0', '1')); // 11111111
console.log('01010101'.replaceAll('0', '1')); // 11111111
- Private Fields Methods
class Employee {
name = "John";
#age=35;
constructor() {
}
#getAge() {
return #age
}
}
const employee = new Employee();
employee.name = "Jack";
employee.#age = 35; // Throws an error
- Static Fields Methods
class Employee{
name = "John";
static #employerName="Github"
static #getEmployerName() {
return #employerName
}
}
const employee = new Employee();
employee.emp = "Jack";
employee.#employerName = 35; // Throws an error
- HasOwn Create
const user = Object.create(null);
user.age = 35;
user.hasOwn('age'); // true
- HasOwn Overwritten
const user = {
age: 35,
hasOwnProperty: ()=> {
return false;
}
};
user.hasOwn('age') // true
- Change Array by Copy
const original = [1, 2, 3, 4];
const reversed = original.toReversed();
console.log(original);
// [ 1, 2, 3, 4 ]
console.log(reversed);
// [ 4, 3, 2, 1 ]
const original = [1, 3, 2, 4];
const sorted = original.toSorted();
console.log(original);
// [ 1, 3, 2, 4 ]
console.log(sorted);
// [ 1, 2, 3, 4 ]
const original = [1, 4];
const spliced = original.toSpliced(1, 0, 2, 3);
console.log(original);
// [ 1, 4 ]
console.log(spliced);
// [ 1, 2, 3, 4 ]
const original = [1, 2, 2, 4];
const withThree = original.with(2, 3);
console.log(original);
// [ 1, 2, 2, 4 ]
console.log(withThree);
// [ 1, 2, 3, 4 ]
💖 💪 🙅 🚩
Himanshu Gupta
Posted on May 11, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.