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'
}
Use
const result = number > 5 ? 'Yes' : 'No'
2. Falsy Shorthand
Instead of
if (value !== null || value !== undefined || value !== ''){
new_value = value
}
Use
new_value = value || 'Hello'
3. Variable Declaration
Instead of
let x
let y
let z = 5
Use
let x, y, z=5
4. For Loop Shorthand
Instead of
const names = ['Mursal', 'Furqan', 'Ali', 'Imran']
for (let i = 0; i < names.length; i++){
console.log(names[i])
}
Use
const names = ['Mursal', 'Furqan', 'Ali', 'Imran']
for (let name of names){
console.log(name)
}
5. Object Property
Instead of
let x=1, y=2
let object = {x:x, y:y}
Use
let x=1, y=2
let object = {x, y}
// You can omit the member name
// If it's same as the variable name
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
}
Use
let volume = (a=0, b=0, c=0) => (a*b*c)
7. Double Bitwise Not
Instead of
Math.floor(4.9) // => 4
Use
~~4.9 // => 4
8. Short-Circuit
Instead of
let dbHost
if (process.env.DB_HOST){
dbHost = process.env.DB_HOST
} else {
dbHost = 'localhost'
}
Use
let dbHost = process.env.DB_HOST || 'localhost'
Top comments (0)