Learn to write JavaScript code more concisely and efficiently with these shorthand techniques. Includes shorthands for declaring variables, assigning values, performing comparisons, writing conditional statements, and working with arrays, objects, and functions.
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.
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.
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"
The traditional JavaScript functions can be simplified with ES6 arrow functions.
//Longhand
function greet(name){
console.log('Welcome ', name)
}
//Shorthand
const great = name => console.log(name)
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
#web-development #javascript-tips #front-end-development #javascript #programming