Posted on: Written by: K-Sato
⚠️ This article was posted over a year go. The information might be outdated. ⚠️

Table of Contents

Only use let if necessary

Using let could cause unnecessary complexity in your code. That said, the important thing is you understand the differences between let, const and var and use them appropriately.

let

  • Variables declared with let can not be redeclared. But you can reassign a new value.
let name = 'John'
console.log(name) //=> John

name = 'Mike'
console.log(name) //=> Mike

let name = 'Nick' //=> SyntaxError: redeclaration of let name

const

  • Variables declared with const can not be redeclared and you can not reassign a new value.
const name = 'John'
console.log(name) //=> John

name = 'Mike' //=> TypeError: invalid assignment to const `name'

const name = 'Nick' //=> SyntaxError: redeclaration of let name

Use Early Return

Use early returns to clean up your code.

if (condition) return

Object Destructuring

Object Destructinrg is another way to clean up your code.

const { created_at: createdAt, password_updated_at: passwordUpdatedAt } = user
const params = { a: "A", b: "B", c: "C" }
const test = ({a, b, c}) => {
  console.log(`${a}${b}${c}`
}

Make your function more succinct

;() => {
  return hoge
}

can be written as:

;() => hoge

Use filter to remove empty strings from an array

.filter(string => string)

Short Circuit Conditionals

if (available) {
  addToCart()
}

Can be written as:

available && addToCart()

Logical Operators

!var: Returns false if its single operand can be converted to true; otherwise, returns true.

if (!user) {
  return 'none'
}

Use a variable for a key in a JavaScript object literal

You can use a variable as a key in object with the brackets notation.

var obj = {
  [key]: value,
}

Conditionally setting a variable

You don’t need to write an extra if-statement if you use this solution.

const timezone = user.preferred_timezone || 'America/New_York'

The code above looks much cleaner compared to the one below.

let timezone = 'America/New_York'
if (user.preferred_timezone) {
  timezone = user.preferred_timezone
}

Format number as currency

number.toLocaleString('en-GB', {
  style: 'currency',
  currency: 'GBP',
})

number.toLocaleString('ja-JP', {
  style: 'currency',
  currency: 'JPY',
})

Check both null and undefined

You can check both null and undefined in one hit with ==.

if (x == null)

If you use ===, it will only be true for values set to null and won’t evaluate as true for undefined variables.

if (x === null)

Extract certain properties from an object

You can do this by using Object Destructuring and Property Shorthand.

const object = { a: 5, b: 6, c: 7 }
const picked = (({ a, c }) => ({ a, c }))(object)

console.log(picked) // { a: 5, c: 7 }

or

interface ISpecific {
  name: string
}

const someObject = {
  name: 'Fenton',
  age: 21,
}

let { age, ...subset } = someObject

Add object to an array

interface Obj {
  name: string
}

const arr: Obj[] = []

const obj1 = { name: 'K-Sato' }

const newArray = [...arr, obj1]
console.log(newArray) //=> [{{ name: "K-Sato" }}]

or

arr.concat(obj1)

console.log(newArray)

Lookup Tables

const howIsBoo = (state) => {
  if (state ===HUNGRY) return 'WANTS FOOD';
  if (state ===SAD) return 'CRYING';
  if (state ===HAPPY) return 'LAUGHING'
  return 'SLEEPING'
}

The code above can be made more efficient by using Objects.

const booFeelsTable = {
  HUNGRY: 'WANTS FOOD',
  SAD: 'CRYING',
  HAPPY: 'LAUGHING',
}
const howIsBoo = state => booFeelsTable[state] || 'SLEEPING'

Naked boolean value

Usually a lot of naked true/false in code is considered a smell.

For instance, the code below

function isNumber(num: number): boolean {
  if (typeof num === 'number') {
    return true
  }
  return false
}

can be written as the code below.

function isNumber(num: number): boolean {
  return typeof num === 'number'
}

Wrapper Class

You can make the code below more expressive without extending the native number prototype by using a wrapper class.

function isLeapYear(year: number): boolean {
  return year % 4 === 0 && (year % 400 === 0 || year % 100 !== 0)
}

export default isLeapYear
class Year {
  dividend: number

  constructor(dividend: number) {
    this.dividend = dividend
  }

  isDivisibleBy(divisor: number): boolean {
    return this.dividend % divisor === 0
  }
}

function isLeapYear(num: number): boolean {
  const year: Year = new Year(num)

  return (
    year.isDivisibleBy(4) &&
    (year.isDivisibleBy(400) || !year.isDivisibleBy(100))
  )
}

export default isLeapYear

URL type

URL is a typescript “built-in” feature in TypeScript.

const url: URL = new URL(`https://urlExample.com`)

Rename & Destructure Variables

You can rename a destructre variabele like the code below.

const data = {
  data1: 'data1',
  data2: 'data2',
}

const { data1: oldData, data2: newData } = data

console.log(oldData, newData)

Use incudes for multiple conditions

if (x === 'a' || x === 'b' || x === 'c' || x === 'd' || x === 'e') {
  console.log('ok')
}

Can be written as the code below using includes.

if (['a', 'b', 'c', 'd', 'e'].includes(x)) {
  console.log('ok')
}

Use … to convert a string into an array

const str = 'kitty'
var newArr = str.split('') // ['k', 'i', 't', 't', 'y'];

can be written as

const newArr = [...str] // ['k', 'i', 't', 't', 'y'];

do something N times

I’ll list 2 examples here.

// create an array
const array: number[] = [...Array(numberOfnestedHeadings)]

// Iterate it with forEach
array.forEach((_: any) => console.log('do something'))
Array.from(Array(3)).forEach((x, i) => {
  console.log('do something')
})

Use a variable in a regular expressions

You can construct a new RegExp object like the code below.s

var replace = 'regex'
var re = new RegExp(replace, 'g')
'mystring'.replace(re, 'newstring')

If you need to use an expression like /\/word\:\w*$/, be sure to escape your backslashes: new RegExp( '\\/word\\:\\w*$' ).

Swap elements in an array

You can use object destructing.

[elements[0], elements[3]] = [elements[3], elements[0]];

or simply do this.

const swap = (i: number, j: number, arr: number[]) => {
  const tmp = arr[j]
  arr[j] = arr[i]
  arr[i] = tmp
}

About the author

I am a web-developer based somewhere on earth. I primarily code in TypeScript, Go and Ruby at work. React, RoR and Gin are my go-to Frameworks.