10 JavaScript Shorthand Coding Techniques That Will Save You Time (And Impress Your Boss!)
Javascript is the most used programming language, with a 78% usage rate among developers.
This really is a must-read for any JavaScript developer. I’ve written this guide to shorthand JavaScript coding techniques that we’ve picked up over the years. To help you understand what is going on, we’ve included the longhand versions to give some coding perspective.
1. The Ternary Operator
It is one of the most popular shorthands in JavaScript. The ternary operator reduces the need to use many lines of code. It actually replaces the if-else statement as follows:
// Longhand
const result;
const mark = 80;
if (mark >= 65) {
return "Pass"
} else {
return "Fail"
}
// Shorthand
const result = mark >= 65 ? "Pass": "Fail";
2. Object destructuring
Besides the traditional dot notation, another way to read the values of an object is by destructuring the object’s values into their own variables.
Suppose you have a person
object with two properties: firstName
and lastName
.
let person = { firstName: 'John', lastName: 'Doe' };
Prior to ES6, when you want to assign properties of the person
object to variables, you typically do it like this:
// Longhand
let firstName = person.firstName;
let lastName = person.lastName;
ES6 introduces the object destructuring syntax that provides an alternative way to assign properties of an object to variables:
// Shorthand
let { firstName: fname, lastName: lname } = person;
In this example, the firstName
and lastName
properties are assigned to the fName
and lName
variables respectively.
3. Arrow function
Functions in JavaScript can be written using arrow function syntax instead of the traditional expression that explicitly uses the function
keyword. Arrow functions are similar to lambda functions in other languages.
// Longhand
function printString(str) {
console.log(`${str},This is a string`);
}
printString('Hello!');
// Shorthand
const printString = (str) => {
console.log(`${str},This is a string`);
}
printString('Hello!')
4. Spread operator
The spread operator, introduced in ES6, has several use cases that make JavaScript code more efficient and fun to use. It can be used to replace certain array functions. The spread operator is simply a series of three dots.
// Longhand
// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()
// Shorthand
// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]
// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];
5. Short circuit evaluation
In JavaScript, short-circuiting is a technique used to optimize code by evaluating only one part of a boolean expression. This means that if the value of the first operand of an AND (&&) expression is false, or the value of the first operand of an OR (||) expression is true, the second operand is not evaluated at all. This behavior can be very useful in certain situations, but it can also lead to unexpected results if not used properly.
Let’s take a closer look at how short-circuiting works in JavaScript. Consider the following code:
// Longhand
let x = '';
let result;
if (x !== null && x !== undefined x!= '') {
result = x;
} else {
result = 'default';
}
// Shorthand
let x = '';
let result = x || 'default';
In this case, the expression x is falsy so ‘default’ will be the result.
6. String to int conversion
One of the essential features of any programming language is the ability to convert data from one type to another.
If we declare a variable as string, say
var x = "10";
By giving typeof() function, we can find that the variable is stored as a “string”.
// Longhand
var x = "10";
y = parseInt(x);
console.log(typeof(y));
// Shorthand
var x = "10";
y = +x;
Instead of using parseInt(), this is a shorthand way to convert string into int in javascript.
7. String repetition
To repeat a string, we have to write a certain amount of code using for loop.
// longhand
let strg = ' ';
for(let i = 0; i < 3; i ++) {
strg += 'Hello \n';
}
console.log(strg);
It can be further simplified by using repeat().
// Shorthand
let strg = "Hello \n";
a = strg.repeat(3);
console.log(a);
In this example, we declare a variable strg
and assign it the value of the string "hello \n". Then, we call the repeat()
method on the strg
variable with an argument of 3
. This means that the string "hello" will be repeated 3 times to create a new string, which we store in the a
variable.
The repeat()
method can also be used with template literals, which allows you to easily create repeated strings with dynamic content. Here's an example:
const name = 'John';
const repeatedGreeting = `Hello ${name}! `.repeat(2);
console.log(repeatedGreeting); // output: "Hello John! Hello John! "
In this example, we declare a variable name
and assign it the value of the string "John". We then use a template literal to create a string that includes the name
variable and the text "Hello!".
We call the repeat()
method on the template literal with an argument of 2
, which means that the entire string (including the variable) will be repeated 2 times.
8. JavaScript For Loop Shorthand
This little tip is really useful if you want plain JavaScript and don’t want to rely on external libraries such as jQuery or lodash.
// Longhand
const fruits = ['mango', 'peach', 'banana'];
for (let i = 0; i < fruits.length; i++)
// Shorthand
for (let fruit of fruits)
If you just wanted to access the index, do:
for (let index in fruits)
This also works if you want to access keys in a literal object:
const obj = {continent: 'Africa', country: 'Kenya', city: 'Nairobi'}
for (let key in obj)
console.log(key); // output: continent, country, city
// Shorthand for Array.forEach:
function logArrayElements(element, index, array) {
console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[2] = 9
9. Implicit Return Shorthand
Return is a keyword we use often to return the final result of a function. An arrow function with a single statement will implicitly return the result its evaluation (the function must omit the braces ({}
) in order to omit the return keyword).
To return a multi-line statement (such as an object literal), it’s necessary to use ()
instead of {}
to wrap your function body. This ensures the code is evaluated as a single statement.
// Longhand
function calcCircumference(diameter) {
return Math.PI * diameter;
}
// Shorthand
calcCircumference = diameter => (
Math.PI * diameter;
)
10. Exponent power shorthand
Another mathematical function with a useful shorthand is the Math.pow()
function. The alternative to using the built-in Math
object is the **
shorthand.
The example below demonstrates this exponent power shorthand in action:
// Longhand
const num = Math.pow(3, 4); // 81
// Shorthand
const num = 3 ** 4; // 81
Conclusion
These are just a few of the most commonly used JavaScript and TypeScript shorthands.
JavaScript and TypeScript longhand and shorthand code typically work the same way under the hood, so choosing shorthand usually just means writing less lines of code. Remember, using shorthand code is not always the best option. What is most important is writing clean and understandable code that other developers can read easily.
What are your favorite JavaScript shorthands? please leave a comment if you know of one!