Tiny, yet very powerful JavaScript function you may have missed published 12/13/2019 | 3 min read

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:

String.prototype.trimStart()
The trimStart() method removes whitespace from the beginning of a string. trimLeft() is an alias of this method.
String.prototype.trimEnd()
The trimEnd() method removes whitespace from the end of a string. trimRight() is an alias of this method.
Object.fromEntries()
The Object.fromEntries() method transforms a list of key-value pairs into an object.
Array.prototype.flat()
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Array.prototype.flatMap()
The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1, but flatMap() is often quite useful, as merging both into one method is slightly more efficient.
Electron | Build cross platform desktop apps with JavaScript, HTML, and CSS.
Build cross platform desktop apps with JavaScript, HTML, and CSS.
React Native · A framework for building native apps using React
A framework for building native apps using React
Native mobile apps with Angular, Vue.js, TypeScript, JavaScript - NativeScript
Free, open source mobile framework. Build truly native iOS and Android mobile apps. Get 100% native API access with JavaScript, TypeScript, Vue.js, or Angular.
Node.js
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.


You may also like reading: