DEV Community

Cover image for JavaSript Shorthands
Mursal Furqan Kumbhar
Mursal Furqan Kumbhar

Posted on

JavaSript Shorthands

JavaScript is one of the most widely used and fastest growing language for Web Development. It is necessary for us, the developers to use the best coding practices to save our time along with the processing resources. Here are SOME of the shorthand, developers can use to save their time.

For any questions and queries, ping me on LinkedIn.

1. Ternary Operator

Instead of

if (number > 5) {
     result = 'Yes'
} else {
     result = 'No'
}
Enter fullscreen mode Exit fullscreen mode

Use

const result = number > 5 ? 'Yes' : 'No'
Enter fullscreen mode Exit fullscreen mode

2. Falsy Shorthand

Instead of

if (value !== null || value !== undefined || value !== ''){
     new_value = value
}
Enter fullscreen mode Exit fullscreen mode

Use

new_value = value || 'Hello'
Enter fullscreen mode Exit fullscreen mode

3. Variable Declaration

Instead of

let x
let y
let z = 5
Enter fullscreen mode Exit fullscreen mode

Use

let x, y, z=5
Enter fullscreen mode Exit fullscreen mode

4. For Loop Shorthand

Instead of

const names = ['Mursal', 'Furqan', 'Ali', 'Imran']

for (let i = 0; i < names.length; i++){
     console.log(names[i])
}
Enter fullscreen mode Exit fullscreen mode

Use

const names = ['Mursal', 'Furqan', 'Ali', 'Imran']

for (let name of names){
     console.log(name)
}
Enter fullscreen mode Exit fullscreen mode

5. Object Property

Instead of

let x=1, y=2
let object = {x:x, y:y}
Enter fullscreen mode Exit fullscreen mode

Use

let x=1, y=2
let object = {x, y}
// You can omit the member name
// If it's same as the variable name
Enter fullscreen mode Exit fullscreen mode

6. Default Parameter

Instead of

function volume(a, b, c){
     if (a === undefined){
          a = 0
     }
     if (b === undefined){
          b = 0
     }
     if (c === undefined){
          c = 0
     }
     return a*b*c
}
Enter fullscreen mode Exit fullscreen mode

Use

let volume = (a=0, b=0, c=0) => (a*b*c)
Enter fullscreen mode Exit fullscreen mode

7. Double Bitwise Not

Instead of

Math.floor(4.9) // => 4
Enter fullscreen mode Exit fullscreen mode

Use

~~4.9 // => 4
Enter fullscreen mode Exit fullscreen mode

8. Short-Circuit

Instead of

let dbHost
if (process.env.DB_HOST){
     dbHost = process.env.DB_HOST
} else {
     dbHost = 'localhost'
}
Enter fullscreen mode Exit fullscreen mode

Use

let dbHost = process.env.DB_HOST || 'localhost'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)