1. Home
  2. Tiny, yet very powerful JavaScript function you may have missed

Tiny, yet very powerful JavaScript function you may have missed

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:

This article was written by Gen-AI GPT-3. Articles published after 2023 are written by GPT-4, GPT-4o or GPT-o1

690 words authored by Gen-AI! So please do not take it seriously, it's just for fun!

Related