javascript

Tiny, yet very powerful JavaScript function you may have missed

JavaScript is powerful, it's proving its strength every day, we use it all the way from web frontends, to desktop apps (electron) to mobile apps (react native, nativescript,..), all the way to the backend (node).

Hello everyone, welcome to a new devspedia story. Today's story is small, and straight to the point, here are a few JavaScript native functions that you maybe missing or didn't know exists.

Trimming strings

We often use .trim(); with strings in order to trim whitespaces, however, there is also .trimStart(); and .trimEnd(); to trim white spaces at the beginning or the end of a string.

Flatten an array

We have always used lodash to flatten an array, however, an array natively has 2 functions for this purpose, .flat(); and .flatMap();, you can use .flat to flatten an array of arrays, or .flatMap to flatten an array of basically anything, as it take a function parameter, and behaves very similar to .map();.

Create an object from a hashmap, or the opposite

To create an object from a hashmap (ex: const a = [ ['a', 1], ['b', 2] ]) you can easily pass this hashmap to const b = Object.fromEntries(a); and it'll return "a": 1, "b": 2;

You can reverse that by passing this result object to Object.entries(b); which will give you [ ['a', 1], ['b', 2] ] again.


That's all, thanks for reading devspedia, I love you, and I'll see you the next time :)

References: