5 Lesser-Known but Useful JavaScript Functions

Valerii M. - Aug 22 - - Dev Community

Introduction:

JavaScript is a powerful language with many built-in functions that often go unnoticed or are forgotten by developers. In this post, I'll introduce you to five such functions that can significantly simplify your work.

1. Array.prototype.flat()

Dealing with arrays of arrays? flat() is here to help! This function returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

const arr = [1, [2, [3, [4]]]];
console.log(arr.flat(2)); // [1, 2, 3, [4]]
Enter fullscreen mode Exit fullscreen mode

2. String.prototype.padStart() and padEnd()

Need to add characters to the beginning or end of a string? These functions are your go-to solution. They're handy for creating strings of a fixed length, for example.

const str = '42';
console.log(str.padStart(5, '0')); // '00042'
Enter fullscreen mode Exit fullscreen mode

3. Optional Chaining (?.)

This operator allows you to safely access deeply nested properties of an object without needing to check each one for existence.

const user = { name: 'John', address: { city: 'NY' } };
console.log(user?.address?.city); // 'NY'
console.log(user?.contact?.phone); // undefined
Enter fullscreen mode Exit fullscreen mode

4. Promise.allSettled()

When you need to handle multiple promises, but you're interested in the outcome of each one, regardless of whether it was fulfilled or rejected, use Promise.allSettled().

const promises = [Promise.resolve(1), Promise.reject('Error'), Promise.resolve(3)];
Promise.allSettled(promises).then(results => console.log(results));
Enter fullscreen mode Exit fullscreen mode

5. Intl.DateTimeFormat

Want to format dates correctly for different locales? This built-in object has you covered.

const date = new Date();
const formatter = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
console.log(formatter.format(date)); // 'August 23, 2024'
Enter fullscreen mode Exit fullscreen mode

Conclusion:

These functions are just a small part of what JavaScript has to offer. Try them out in your next project and see how they can make your development life easier!

.
Terabox Video Player