10 great JavaScript tricks that will improve your productivity

These top tips and tricks will help you dramatically increase your productivity while coding in any JavaScript project.

Get unique values from an array

const array = [5,3,7,6,4,5,5,7,5];
const uniqueArray = [...new Set(array)];

console.log(uniqueArray);

The Set constructor takes an optional array as its first argument. Send your array into a new Set and then destructuring to spread those now unique values onto a new array.

[5, 3, 7, 6, 4]

Lookup deeply nested properties

const data = {a: {deeply: {nested: {message: 'hello'}}}};

console.log('existing "path":', data.a?.deeply?.nested?.message);
console.log('missing "path":', data.a?.deeply?.nestedAndNonExisting?.message);

Optional chaining allows you to access deeply nested properties without the need to wrap your code in complex conditionals. If a property is missing somewhere in the middle the code will not crash but instead stop the lookup and return undefined.

existing "path": hello
missing "path": undefined

Do note that you cannot optional chain the base variable (data in the example above) without first declaring it.

Merge objects and properties together

function fly() {
  console.log(`${this.name} flew away!`);
}

const bird = {hasWings: true, numberOfLegs: 2, fly};
const swimmer = {canSwim: true};

const polly = {...bird, ...swimmer, name: 'Polly', age: 4};

console.log(polly);
polly.fly();

The destructuring assignment is very powerful when you want to merge objects, keep in mind that this is not a deep merge, so the pre-existing key would be overwritten by the last object or property with the same key name.

They can also be used for object composition as an alternative for class-based inheritance as can be seen with the fly function above. Some might say object composition is more like the fundamental idea of how JavaScript's object system was supposed to work over the class syntax that was added fairly recently.

{
  hasWings: true,
  numberOfLegs: 2,
  fly: [Function: fly],
  canSwim: true,
  name: 'Polly',
  age: 4
}

Polly flew away!

Pretty print Objects as formatted strings

const data = [
  {name: 'Anna', birthDate: '1964-12-05'},
  {name: 'Jenny', birthDate: '1987-02-19'},
  {name: 'Ola', birthDate: '2012-07-23'},
];

console.log(JSON.stringify(data, undefined, '  '));

JSON stringifying objects with the third argument as two spaces will pretty-print the object with all its child objects and arrays.

[
  {
    "name": "Anna",
    "birthDate": "1964-12-05"
  },
  {
    "name": "Jenny",
    "birthDate": "1987-02-19"
  },
  {
    "name": "Ola",
    "birthDate": "2012-07-23"
  }
]

This is super useful when debugging in Node.js as it truncates deeply nested object when logging them directly.

It's also really nice in the terminal as well to write data to files when debugging.

$ nodemon main.js > result.json

Log variables name and value without naming them while debugging

const someData = 'Lorem ipsum dolor';
const otherData = 123;
console.log({someData, otherData});

Just wrap your variables in an object so that it will print the variable name as the key in the object along with its value.

{someData: 'Lorem ipsum dolor', otherData: 123}

Find a single object in an array

const data = [
  {name: 'Anna', birthDate: '1964-12-05'},
  {name: 'Jenny', birthDate: '1987-02-19'},
  {name: 'Ola', birthDate: '2012-07-23'},
];

const jenny = data.find((person) => person.name === 'Jenny');
const missingPerson = data.find((person) => person.name === 'Jacob');

console.log({jenny, missingPerson});

The array function find is amazingly simple and useful. It will return undefined of no object matched.

{
  jenny: {name: 'Jenny', birthDate: '1987-02-19'},
  missingPerson: undefined
}

Remove falsy objects from an array

const data = ['lorem', '', 'ipsum', undefined, false, 'dolor'];

console.log(data.filter(Boolean));

Passing the Boolean constructor function as an argument to the Array.prototype.filter function will return a new array without any falsy values.

['lorem', 'ipsum', 'dolor']

Falsy values are one of:

  • undefined
  • null
  • NaN
  • 0
  • '' (empty string)
  • false

Get the last item in an array

let array = [0, 1, 2, 3, 4, 5];
console.log('the last number is', array.slice(-1)?.[0]);

Array.prototype.slice can take negative values where -1 will return an array with the last value, -2 the last two values. If you combine -1 with optional chaining you will get the last value directly (or undefined if array length is 0).

the last number is 5

Truncate an Array

const array = [1, 2, 3, 4, 5, 6];
array.length = 2;

console.log(array);

Did you know that setting the length of an existing array will drop any values after that length?

[1, 2]

You can also empty the array by setting its length to 0.

Wait for multiple async function calls

(async () => {
  const promises = [
    Promise.resolve(123),
    Promise.reject(undefined),
    new Promise((resolve) => setTimeout(() => resolve('The great result'), 100)),
    Promise.reject(new Error('There was an error'))
  ];

  const results = await Promise.allSettled(promises);

  console.log(results);
})();

Working with Promises is now easier than ever. You can now collect the results from multiple parallel async calls into a single result array containing both the fulfilled and rejected results with Promise.allSettled.

[
  { status: 'fulfilled', value: 123 },
  { status: 'rejected', reason: undefined },
  { status: 'fulfilled', value: 'The great result' },
  {
    status: 'rejected',
    reason: 'Error: There was an error'
  }
]

If you rather only want the fulfilled results and handle the errors in a catch you can use Promise.all instead.

Keep adding to your tinkering tricks!