JavaScript time-saving tricks

Knowing simple JS tricks can save a lot of development time, so I will share with you some tricks I learned these days and I found useful:

Object destructuring used to simulate name parameters

A very nice and handy way to pass a config object as a parameter for a function and avoid checking the existence of each field you need. Also, in this case, you can assign default values for some fields, in case they are not provided.

In the gist below I show the old and the new way. “withoutDestruct” function takes a JS object as a parameter and use ugly verbose logic to fetch each option. This is a perfectly working version of doing things but thanks to ES2015 object destructuring this kind of task can be solved easily and faster (check withDestruct function definition in the gist below)

Object destructuring for array elements

Here is a nice way of assigning specific elements of an array to variables. I find this useful when I have a string, I want to split it by a separator and extract only some of the elements returned (similar to regex capturing groups). In the gist below there are some lines of code to show differences.

Array truncation or cleaning

An array can be truncated or cleaned simply by changing its length property.

var data = ["a", "b", "c", "d", "e", "f", "g", "h"];
// Truncate
data.length = 5;
console.log(data); //=>  ["a", "b", "c", "d", "e"]

// Clean
data.lenth = 0;
console.log(data); // []

Remove duplicates from an array

This simple task can be performed in multiple ways. Here is a smart and simple way of doing this  by using spread operator and ES2015 Set.

const data = [1, 2, 3, 4, 5, 2, 3, 5, 6, 3, 1, 1, 2, 3, 2, 2];
console.log([... new Set(data)]); //=> (6) [1, 2, 3, 4, 5, 6]

Convert to boolean using !!

const t = "true";
console.log(!!t); //=> true

const f = "false";
console.log(!!f); //=> false

const abc = "thisisastring";
console.log(!!abc); //=> true;

const undef = undefined;
console.log(!!undef); //=> false

const nilVal = nil;
console.log(!!nilVal); //=> false

Await multiple async calls

Waiting for multiple async calls to finish is possible using Promise.all and, of course, await:

awayt Promise.all([async1(), async2(), async3])

JSON pretty print

I work with JSON almost every day and I often need to pretty print structures for better visualization. Recently I learned that JSON.stringify can format the output if I use the other parameters. The third parameter of this function represents the number of spaces used to format the output.


1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 4.80 out of 5)