Javascript Baker’s Dozen

Javascript Baker’s DozenTuan Pham-BarnesBlockedUnblockFollowFollowingJun 12Photo by Florencia Viadana on UnsplashThrough 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.

Forced BooleanTo force a variable into a Boolean value without changing its value:const myBoolean = !!myVariable;The double NOTs (!!) is needed to keep the intent of the boolean value and prevent it from flipping truthiness.

2.

De-dupeTo 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 PropertyTo conditionally set a property on an object, using the spread operator:const myObject = { .

myProperty && { propName: myPoperty } };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.

4.

Merge ObjectsTo 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 VariablesTo 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.

Destructing allows this to happen within an internal mechanism.

6.

Remove Falsy ValuesTo 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 TypesTo 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 AliasesReassigning 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 CodeTo 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 ArrayTo 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 CodeTo 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 ArrayTo 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 CloneThis 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 ExtendThere 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.

.. More details

Leave a Reply