Javascript Baker’s Dozen

Tuan Pham-Barnes
The Startup
Published in
4 min readJun 12, 2019
Photo by Florencia Viadana on Unsplash

Through the decades of writing Javascript code, with its evolution from a front-end scripting language to a bonafide powerhouse, I’ve picked up some great one-liners. No, not those one-liners, but a piece of code so terse, you will be amazed at how powerful they are. But with great power, comes great responsibility — use it sparingly to avoid obfuscating the code into unreadable spaghetti.

Here are 13 of my favorite Javascript one-liners in no particular order.

*All examples using Node.js v11.x. Your usage may vary on client-side browsers.

1. Convert to Boolean

To convert a variable into a Boolean value without changing the original value:

const myBoolean = !!myVariable;

The double NOTs (!!) is needed to keep the intent of the boolean value and prevent it from flipping truthiness. myVariable will not change, but the conversion would be assigned as a Boolean to myBoolean.

2. De-dupe

To remove duplicates from an array:

const deDupe = [...new Set(myArray)];

Each value of a Set is required to be unique, combining it with the spread operator will yield a de-duped array from myArray.

3. Conditional Property

To conditionally set a property on an object, using the spread operator on an object:

const myObject = { ...myProperty && { propName: myValue } };

If the spread result is empty, then the && fails and does not set the new property; otherwise, if not empty, the && will override and set the property.

Another way to conditionally set a property on an object using a boolean expression:

const myObj = { propOne: "a", ...(booleanExpr && { propTwo: "b" })}

4. Merge Objects

To merge objects:

const mergedObject = { ...objectOne, ...objectTwo };

Supports unlimited merging, but if there are shared properties between objects, the right-most object with the duplicate property name will overwrite the other object’s property. *Note this is for a shallow merge only.

5. Swapping Variables

To swap values of two variables without using an intermediary:

[varA, varB] = [varB, varA];

The value of varA is now the value of varB and vice versa. Destructuring allows this to happen within an internal mechanism.

6. Remove Falsy Values

To remove all falsy values from an array:

const clean = dirty.filter(Boolean);

This will remove anything that equates to Boolean false, which includes: null, undefined, false, zero (0), and empty string.

7. Convert Element Types

To convert Number elements to String elements:

const stringArray = numberArray.map(String);

If the array contains a string, it will remain a string.
This can also be used to convert String elements to Number type:

const numberArray = stringArray.map(Number);

8. Destructuring Property Aliases

Reassigning property values from one object to another:

const { original: newName } = myObject;

This will initialize a new variable called newName and assign it with the value from myObject.orginal.

9. Format JSON Code

To display JSON code in a human-readable format:

const formatted = JSON.stringify(myObj, null, 2);

The stringify command takes three parameters. The first is the Javascript object. The second is an optional function that can be used to act on the JSON as it’s being stringified. The last parameter indicates how many spaces to add as an indent to format the JSON. Omitting the last parameter, the JSON would return as one long line. This will fail if there is a circular reference in myObj.

10. Quick Number Array

To create an array and fill it with numbers, indexed by zero:

const numArray = Array.from(new Array(52), (x, i) => i);

The array size can be a literal or a variable. This is an example to create 52 elements used for a deck of cards.

11. Generate 2FA Code

To generate a six-digit code for 2FA or other validation code:

const code = Math.floor(Math.random() * 1000000).toString().padStart(6, "0");

Match the number of zeros in the random range with the padStart targetLength parameter.

12. Shuffle Array

To shuffle an array without knowing the context of the values:

myArray.sort(() => { return Math.random() - 0.5});

A better sorting algorithm is the Fisher-Yates shuffle that I’ve written about in my Javascript Shuffle article.

13. Deep Clone

This one is not very performant, but if you need a quick one-liner, then this cloning method can be used to deep copy an object:

const myClone = JSON.parse(JSON.stringify(originalObject));

If originalObject has a circular reference, then this will fail. Use this technique on simple objects that you create yourself.

Using the spread operator can create a shallow clone:

const myClone = { ...orignalObject };

Combine and Extend

There are numerous ways to combine these one-liners to perform feats of magic with very little code. Javascript will continue to evolve with additional super-powers to allow developers to reduce the size of their codebase. Use these one-liners to extend your skills and write code faster.

--

--

Tuan Pham-Barnes
The Startup

I write code, flash fiction, commentary, and poetry; sometimes my code reads like poetry and my fiction becomes flash commentary!