Learn these neat JavaScript tricks in less than 5 minutes

Time-saving techniques used by pros

Alcides Queiroz
Apr 22, 2018 · 3 min read
Image for post
Image for post

1. Clearing or truncating an array

An easy way of clearing or truncating an array without reassigning it is by changing its length property value:

const arr = [11, 22, 33, 44, 55, 66];

2. Simulating named parameters with object destructuring

Chances are high that you’re already using configuration objects when you need to pass a variable set of options to some function, like this:

doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 });

This is an old but effective pattern, which tries to simulate named parameters in JavaScript. The function calling looks fine. On the other hand, the config object handling logic is unnecessarily verbose. With ES2015 object destructuring, you can circumvent this downside:

function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) {
// ...
}

And if you need to make the config object optional, it’s very simple, too:

function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) {
// ...
}

3. Object destructuring for array items

Assign array items to individual variables with object destructuring:

const csvFileLine = '1997,John Doe,US,john@doe.com,New York';

4. Switch with ranges

NOTE: After some thought, I’ve decided to differentiate this trick from the others in this article. This is NOT a time-saving technique, NOR is it suitable for real life code. Keep in mind: “If”s are always better in such situations.
Differently from the other tips in this post, it is more a curiosity than something to really use.
Anyway, I’ll keep it in this article for historical reasons.

Here’s a simple trick to use ranges in switch statements:

function getWaterState(tempInCelsius) {
let state;

switch (true) {
case (tempInCelsius <= 0):
state = 'Solid';
break;
case (tempInCelsius > 0 && tempInCelsius < 100):
state = 'Liquid';
break;
default:
state = 'Gas';
}

5. Await multiple async functions with async/await

It’s possible to await multiple async functions to finish by using Promise.all:

await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])

6. Creating pure objects

You can create a 100% pure object, which won’t inherit any property or method from Object (for example, constructor, toString() and so on).

const pureObject = Object.create(null);

7. Formatting JSON code

JSON.stringify can do more than simply stringify an object. You can also beautify your JSON output with it:

const obj = { 
foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } }
};

8. Removing duplicate items from an array

By using ES2015 Sets along with the Spread operator, you can easily remove duplicate items from an array:

const removeDuplicateItems = arr => [...new Set(arr)];

9. Flattening multidimensional arrays

Flattening arrays is trivial with Spread operator:

const arr = [11, [22, 33], [44, 55], 66];

Unfortunately, the above trick will only work with bidimensional arrays. But with recursive calls, we can make it suitable for arrays with more than 2 dimensions:

function flattenArray(arr) {
const flattened = [].concat(...arr);
return flattened.some(item => Array.isArray(item)) ?
flattenArray(flattened) : flattened;
}

And there you have it! I hope these neat little tricks help you write better and more beautiful JavaScript.

freeCodeCamp.org

This is no longer updated.

Alcides Queiroz

Written by

JavaScript hacker, front-end engineer and F/OSS lover. ☞ github.com/alcidesqueiroz ☜ ☞ alcidesqueiroz.com ☜ ☞ twitter.com/alcidesqueiroz ☜

freeCodeCamp.org

This is no longer updated. Go to https://freecodecamp.org/news instead

Alcides Queiroz

Written by

JavaScript hacker, front-end engineer and F/OSS lover. ☞ github.com/alcidesqueiroz ☜ ☞ alcidesqueiroz.com ☜ ☞ twitter.com/alcidesqueiroz ☜

freeCodeCamp.org

This is no longer updated. Go to https://freecodecamp.org/news instead

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store