Javascript Shorthand Coding Techniques

In this blog post, I have compiled some helpful javascript shorthand coding techniques. Javascript shorthands are good coding techniques that can help programmers optimize and simplify their javascript codes.

1. If Presence

At a point in our code, we need to check if a variable is present or not. The if present shorthand helps you achieve that with a simple code.

// Longhand
if(isGirl === true){
  console.log('isGirl')
}
//Shorthand
if(isGirl){
  console.log('isGirl')
}

Note: The shorthand in the example above will evaluate as long as isGirl is a truthy value.

2. Ternary Operator

We can use the conditional (ternary) operator instead of the if ... else statement in just one line of code.

//Longhand
const age = 19;
let status;
if(age > 18){
  status = "An adult"
}else{
  status = "Young"
}
//Shorthand
const status = age > 18 ? "An Adult" : "Young"

3. Arrow Function

The traditional javascript functions can be simplified with ES6 arrow functions.

//Longhand
function greet(name){
  console.log('Welcome ', name)
}
//Shorthand
great = name => console.log(name)

4. Destructuring Assignment

Destructuring assignment will not only save a lot of time makes your code cleaner and simpler.

const vehicles = {
  car: "๐Ÿš—",
  taxi: "๐Ÿš•",
  bus: "๐ŸšŒ",
  minibus: "๐Ÿš"
};
// Longhand
let car = vehicles.car
let taxi = vehicles.taxi
let bus = vehicles.bus
let minibus = vehicles.minibus
// Shorthand
const { car, taxi, bus, minibus } = vehicles

5. For Loop

The example below used for ... of and for ... in which is simplified the code.

const animals = ["goat", "sheep", "dog", "cat"]
// Longhand
for (let i=0; i < animals.length; i++){
  console.log(animals[i])
}
// Shorthand
for(let animal of animals){
  console.log(animal)
}
// Getting the index
for(let index in animals){
  console.log(animals[index])
}

6. Template Literals

It is common to use '+' to concatenate multiple string variables. ES6 template literals make it much easier with backtick and ${}.

// Longhand
const checkOut = 'Order price: ' + price + ' at a discount of ' + discount
// Shorthand
const checkOut = `Order price: ${price} at a discount of ${discount}`

7. Multi-line String

Writing lines of string in code is made much easier with backticks.

// Longhand
const msg = 'A wonderful serenity has taken possession\n\t'
    + 'of my entire soul, like these sweet mornings of spring\n\t' 
    +'which I enjoy with my whole heart. I am alone,\n\t' 
    +'and feel the charm of existence in this spot,\n\t' 
    +'which was created for the bliss of souls like mine.\n\t '
//Shorthand
const msg = `A wonderful serenity has taken possession
    of my entire soul, like these sweet mornings of spring 
    which I enjoy with my whole heart. I am alone, 
    and feel the charm of existence in this spot, 
    which was created for the bliss of souls like mine.` 

8. Exponent Power

// Longhand
Math.pow(5,3) // 125
// Shorthand
5**3 // 125

9. Declaring Variables

Shorthand can save you a lot of time when declaring multiple variables.

// Longhand
let a;
let b = 6;
let c;
// Shorthand
let a, b = 6, c;

10. Default Parameter Values

ES6 makes it possible to assign default to variables in the function declaration.

//Longhand
function checkOut(quantity, price, discount){
  if(discount === undefined){
    discount = 0
  }
  return quantity * price + discount
}
// Shorthand
checkOut = (quantity, price, discount) => (quantity * price + discount)

11. Array.find

const animals = [
  {name: 'octopus', animalClass: 'invertebrates'},
  {name: 'shark', animalClass: 'fish'},
  {name: 'toad', animalClass: 'amphibians'},
  {name: 'snake', animalClass: 'reptiles'},
  {name: 'ostrich', animalClass: 'birds'},
  {name: 'cat', animalClass: 'mammals'},
]
//Longhand
function findReptile(name){
  for(let i=0; i < animals.length; ++i){
    if(animals[i].animalClass === 'reptiles' && animals[i].name === name){
      return animals[i]
    }
  }
}
// Shorthand
findReptile = name => (
  animals.find(animal => animal.animalClass ==='reptiles' && animal.name === name)
) 

12. Short-circuit Evaluation

Using a short-circuit logical operator helps reduce the number of lines of code to one.

// Longhand
let person;
if(job){
  person = job
}else{
  person = 'unemployed'
}
// Shorthand
const person = job || 'unemployed'

13. Converting a String into a Number

Converting a string to number can be done easily without using parseInt or parseFloat.

// Longhand
const quantity = parseInt("250")
const price = parseFloat("432.50")
// Shorthand
const quantity = +"250" // converts to int
const price = +"432.50" // converts to float

14. Spread Operator

I have seen a lot of developers use [].concat() to join two arrays together and array.slice() to clone an array. But this can be done easily with the Javascript ES6 spread operator.

const birds = ["parrot", "swan", "eagle", "duck"]
// Longhand
// joining arrays
const animals = ["zebra", "giraffe", "llama", "raccoon"].concat(birds)
// cloning arrays
const newBirds = birds.slice()
// Shorthand
// joining arrays
const animals = ["zebra", "giraffe", "llama", "raccoon", ...birds]
//cloning arrays
const newBirds = [...birds]

15. Null, Undefined, Empty Checks

Performing an action when a variable is undefined, null or empty can be done simply with shorthand.

// Longhand
if(variable !== undefined || variable !== "" || variable !== null){
  console.log(variable)
}
// Shorthand
if(varible){
  console.log(variable)
}
// assigning variable to newVariable when variable is truthy
let newVariable = variable || ""

16. Decimal Base Exponents

Typing 1e4 is easier and cleaner than typing 10000.

// Longhand
for(let i; i < 1000000; i++){}
// Shorthand
for(let i; i < 1e6; i++){}
// evaluates to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;

17. Object Property

In ES6 we can easily assign properties to objects. You can take advantage of the shorthand notation if the variable name is the same as the object key.

const quantity = 324, price = 45.50;
// Longhand
const product = {quantity: quantity, price: price}
// Shorthand
const product = {quantity, price}

18. Implicit Return

With an arrow function, you can return an implicit result in a line of code.

// Longhand
  function area(radius){
    return Math.PI * radius**2
  }
  //Shorthand
  area = radius => Math.PI * radius**2
  // return multi-line statement
  area = radius => (
    Math.PI * radius**2
  )

These are the few shorthands I have gathered together in this post. I would love to find more, please post in the comment the shorthands you find useful.

4 responses to “Javascript Shorthand Coding Techniques”

  1. johny why Avatar
    johny why

    hi, great tips! Suggestion on “11. Array.find”, put “Long-hand” after the array is declared, cuz that’s needed for both versions. thx!

  2. Kim Avatar
    Kim

    hi, great tips! may I take this article to my blog?
    Can I use it?

    1. Clemence Ayekple Avatar
      Clemence Ayekple

      Yes, but you have to reference the article.

  3. […] not only make your life easier but also makes you write clean as well. I have another article on Javascript Shorthand Coding Techniques that discussed 18 different shorthand techniques in […]

Leave a Reply

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

Attach images – Only PNG, JPG, JPEG and GIF are supported.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Quote of the week

"People ask me what I do in the winter when there's no baseball. I'll tell you what I do. I stare out the window and wait for spring."

~ Rogers Hornsby

All rights resolved