Javascript Shorthand Coding Techniques
Tags: javascript, codenewbie, todayilearned, webdev
Published: 2020-01-26 10:02:26

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.
```js
// 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) instead of the ``if ... else`` statement in just one line of code.

```js
//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.
```js
//Longhand
function greet(name){
  console.log('Welcome ', name)
}

//Shorthand
great = name => console.log(name)
```
## 4. Destructuring Assignment
[Destructuring assignment](https://anansewaa.com/javascript-es6-array-and-object-destructuring/) will not only save a lot of time makes your code cleaner and simpler.
```js
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.
```js
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 ``${}``.
```js
// 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.
```js
// 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
```js
// 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.
```js
// 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.
```js
//Longhand
function checkOut(quantity, price, discount){
  if(discount === undefined){
    discount = 0
  }
  return quantity * price + discount
}

// Shorthand
checkOut = (quantity, price, discount = 0) => (quantity * price - discount)
```
## 11. Array.find
```js
//Longhand
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'},
]

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.
```js
// 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``.
```js
// 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**.
```js
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.
```js
// 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.
```js
// 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.
```js
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.
```js
// 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.