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 = 0) => (quantity * price - discount)
11. Array.find
//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.
// 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.
Top comments (15)
12 and 15 is well-known to be quite dangerous, that is why rather than
This is safer
Without
??
, I do have to write my own utility function sometimes.Thanks
For #1:
if(isGirl)
is not a shorthand forif(isGirl === true)
because the first condition will always pass if the value is truthy whereas later will only pass if the value is boolean true.For #3: Arrow function is not a shorthand for the traditional function. Because arrow functions are lexical meaning
this
inside an arrow function will only have lexical scope. So it can not be bind, call or applied against another context.For #12 and #15 see this commented
Also, the arrow function in this case isn't hoisting,
function expressions (aka the longhand) will hoist.
For #5, why not
Array.prototype.forEach
?Because
forEach
does not return anything. You might need to use the returned value somewhere out of your callback.I'm not sure I understand. A regular for loop doesn't return anything either. This is equivalent to the examples he gave, but it's more legible and compact.
Both forEach and for of can be used, forEach is used in arrays while for of can be used in arrays,maps,set or any iterable member objects.
forEach
can also be used with arrays, maps, and sets. To my knowledge, the only advantage that a traditionalfor
loop has is the ability to traverse objects.But note that this is not a traditional for loop, this is a "for of", it even can loop through Strings (instead of converting a string to an array or using a for with the length)
I think the only advantage that I see to use the for loop is having one common way to loop through elements, or if you have a function that can have different iterable object types, example:
const loopThrough = (object) => {
for(const n of object) {
console.log(n);
}
};
loopThrough("hello");
loopThrough(["h","e","l","l","o"]);
loopThrough(new Set([1, 2, 3, 4, 5]));
// Longhand
const quantity = parseInt("250")
const price = parseFloat("432.50")
// Shorthand
const quantity = +"250" // converts to int
const price = +"432.50" // converts to float
I have a habbit of using parseInt parseFloat everytime.I would surely follow this shorthand.
This is fire!! 🔥🔥🔥 I've bookmarked this and will share it out for sure! Appreciate all the edit suggestions in the comments as well! Great work Ayekple!
I guess 10. should be
Thanks
Also logically, wouldn't you want to subtract the discount?