JavaScript Tips

Useful JavaScript Tips — Loops and Sorting Dates

Spread the love

Like any kind of apps, JavaScript apps also have to be written well. Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Break Out of a for Loop

If we want to end a for loop early, we can use the break keyword.

For instance, we can write:

for (const val of list) {
  if (val === 'b') {

If val is 'b' then we end the loop with break .

We can also do the same with an old for loop:

for (let i = 0; i < list.length; i++) {
  if (list[i] === 'b') {

We do the same thing, except it’s longer because of the indexes.

Check if an Object is Empty

We can check if an object is empty with the Object.entries method. It returns the non-inherited key-value pairs in an object.

Therefore, we can write:

Object.entries(obj).length === 0

to check if obj is empty by checking the array returned by Object.entries ‘s length.

It’s a good idea to check that obj is actually by adding:

obj.constructor === Object

Lodash also has the isEmpty function to do the same thing.

We can write:


to do the check.

Return the Result of an Async Function

An async function returns a promise with the resolved value of the promise.

For instance, if we write:

const getJSON = async () => {
  const response = await fetch('./file.json')
  return response

then we return a promise that resolves to the response object. We can then use it with other async functions or call then on it.

Check if a JavaScript Array has a Given Value

We can use the includes method to check if an array has the given value.

For instance, we can write:

['red', 'green'].includes('red');

Then we can check if 'red' is in the array it’s called on. It should return true since it’s included in the array. If the value in the argument isn’t included, then it returns false .

Rename Fields When Object Destructuring

We can rename fields when we’re destructuring objects. To do that, we can use the : symbol to do it.

For instance, we can write:

const person = {
  firstName: 'james',
  lastName: 'smith'

const { firstName: name, lastName } = person;

Then we renamed firstName to name. So name is 'james'.

Using Symbols

We can use symbols to create an identifier that’s always unique. Each symbol that’s created won’t be the same even if they have the same content.

For instance:

Symbol() === Symbol()

returns false .

Symbol('foo') === Symbol('foo')

is also false .

We can use them as property identifiers.

For instance, we can write:

const foo = Symbol('foo');
const obj = {

We can also write:

const foo = Symbol('foo');
class Bar {

We can use symbols in both objects and classes as identifiers.

Public Class Fields

We can add public class fields by putting them in constructors or methods.

For instance, we can write:

class Foo {
  constructor() {
    this.count = 0

Sorting an Array by Date

To sort an array by date, we can use the sort method and compute the difference between the dates 2 entries and return it.

For instance, given the following array:

const tasks = [{
    title: 'eat',
    date: new Date('2020-06-23')
    title: 'drink',
    date: new Date('2020-06-10')
    title: 'sleep',
    date: new Date('2020-06-22')

We can sort it by date descending order by writing:

tasks.sort((a, b) => -;

sort sorts an array in place.

The + operator converts dates to UNIX timestamps so that we can compute their difference.

If the difference is more than 1, then sort reverses the order of the 2 entries.

So we get:

    "title": "eat",
    "date": "2020-06-23T00:00:00.000Z"
    "title": "sleep",
    "date": "2020-06-22T00:00:00.000Z"
    "title": "drink",
    "date": "2020-06-10T00:00:00.000Z"

as the value of tasks .

We can flip a and b around to sort tasks in date ascending order.

To make a copy of tasks before sorting, we can use the spread operator or slice as follows:

const sortedTasks = [...tasks];
sortedTasks.sort((a, b) => -;


const sortedTasks = tasks.slice();
sortedTasks.sort((a, b) => -;


We can use break to end a loop early.

To sort objects with dates, we can return the difference between the timestamps.

Also, we can check if an object is empty with Object.entries to return an array of key-value pairs and use the length property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *