JavaScript shorthand tips and tricks that will save your time

The shorthand techniques can help you to write optimized code and let you achieve your goal with less coding. Let’s discuss some of the shorthand tips and tricks of JavaScript one by one.
1. Declaring variables
//Longhand
let x;
let y = 20;
//Shorthand
let x, y = 20;
2. Assigning values to multiple variables
We can assign values to multiple variables in one line with array destructuring.
//Longhand
let a, b, c;
a = 5;
b = 8;
c = 12;
//Shorthand
let [a, b, c] = [5, 8, 12];
3. The Ternary operator
We can save 5 lines of code here with the ternary (conditional) operator.
let marks = 26;
//Longhand
let result;
if(marks >= 30){
result = 'Pass';
}else{
result = 'Fail';
}
//Shorthand
let result = marks >= 30 ? 'Pass' : 'Fail';
4. Assigning a default value
We can use OR(||)
short circuit evaluation or Nullish coalescing operator (??) to assign a default value to a variable in case the expected value is found falsy.
//Longhand
let imagePath;
let path = getImagePath();
if(path !== null && path !== undefined && path !== '') {
imagePath = path;
} else {
imagePath = 'default.jpg';
}
//Shorthand 1
let imagePath = getImagePath() || 'default.jpg';
//Shorthand 2
let imagePath = getImagePath() ?? 'default.jpg';
5. AND(&&) Short circuit evaluation
If you are calling a function only if a variable is true, then you can use AND(&&)
short circuit as an alternative for this.
//Longhand
if (isLoggedin) {
goToHomepage();
}
//Shorthand
isLoggedin && goToHomepage();
The AND(&&)
short circuit shorthand is more useful in React when you want to conditionally render a component. For example:
<div> { this.state.isLoading && <Loading /> } </div>
6. Swap two variables
To swap two variables, we often use a third variable. We can swap two variables easily with an array destructuring assignment.
let x = 'Hello', y = 55;
//Longhand
const temp = x;
x = y;
y = temp;
//Shorthand
[x, y] = [y, x];
7. Arrow Function
//Longhand
function add(num1, num2) {
return num1 + num2;
}
//Shorthand
const add = (num1, num2) => num1 + num2;
Reference: JavaScript Arrow function
8. Template Literals
We normally use +
operator to concatenate string values with variables. With ES6 template literals, we can do it in a more simple way.
//Longhand
console.log('You got a missed call from ' + number + ' at ' + time);
//Shorthand
console.log(`You got a missed call from ${number} at ${time}`);
9. Multi-line String
For multiline strings we normally use +
operator with a new line escape sequence (\n
). We can do it in an easier way by using backticks (`
).
//Longhand
console.log('JavaScript, often abbreviated as JS, is a \n' +
'programming language that conforms to the \n' +
'ECMAScript specification. JavaScript is high-level,\n' +
'often just-in-time compiled, and multi-paradigm.');
//Shorthand
console.log(`JavaScript, often abbreviated as JS, is a
programming language that conforms to the
ECMAScript specification. JavaScript is high-level,
often just-in-time compiled, and multi-paradigm.`);
10. Multiple condition checking
For multiple-value matching, we can put all values in an array and use indexOf()
or includes()
method.
//Longhand
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
// Execute some code
}
// Shorthand 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
// Execute some code
}
// Shorthand 2
if ([1, 'one', 2, 'two'].includes(value)) {
// Execute some code
}
11. Object Property Assignment
If the variable name and object key name are the same then we can just mention the variable name in object literals instead of both key and value. JavaScript will automatically set the key same as the variable name and assign the value as a variable value.
let firstname = 'Amitav';
let lastname = 'Mishra';
//Longhand
let obj = { firstname: firstname, lastname: lastname };
//Shorthand
let obj = { firstname, lastname };
12. String into a Number
There are built-in methods like parseInt
and parseFloat
available to convert a string to a number. We can also do this by simply providing a unary operator (+) in front of the string value.
//Longhand
let total = parseInt('453');
let average = parseFloat('42.6');
//Shorthand
let total = +'453';
let average = +'42.6';
13. Repeat a string multiple times
To repeat a string for a specified number of times, you can use a for
loop. But using the repeat()
method we can do it in a single line.
//Longhand
let str = '';
for(let i = 0; i < 5; i ++) {
str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello Hello
// Shorthand
'Hello '.repeat(5);
14. Exponent Power
We can use Math.pow()
method to find the power of a number. There is a shorter syntax to do it with a double asterisk (**
).
// Longhand
const power = Math.pow(4, 3); // 64
// Shorthand
const power = 4**3; // 64
15. Double bitwise NOT operator (~~)
The double bitwise NOT operator is a substitute for Math.floor()
method.
// Longhand
const floor = Math.floor(6.8); // 6
// Shorthand
const floor = ~~6.8; // 6
Improvement from comment by Caleb: The double NOT bitwise operator approach only works for 32 bit integers i.e (2**31)-1 = 2147483647. So for any number higher than 2147483647, bitwise operator (~~) will give wrong results, so recommended to use
Math.floor()
in such case.
16. Find max and min numbers in an array
We can use for loop to loop through each value of the array and find the max or min value. We can also use the Array.reduce() method to find the max and min number in the array.
But using a spread operator we can do it in a single line.
// Shorthand
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2
17. For loop
To loop through an array we normally use the traditional for
loop. We can make use of the for...of
loop to iterate through arrays. To access the index of each value we can use for...in
loop.
let arr = [10, 20, 30, 40];
//Longhand
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
//Shorthand
//for of loop
for (const val of arr) {
console.log(val);
}
//for in loop
for (const index in arr) {
console.log(`index: ${index} and value: ${arr[index]}`);
}
We can also loop through object properties using for...in
loop.
let obj = { x: 20, y: 50 };
for (const key in obj) {
console.log(obj[key]);
}
Reference: Different ways to iterate through objects and arrays in JavaScript
18. Merging of arrays
let arr1 = [20, 30];
// Longhand
let arr2 = arr1.concat([60, 80]);
// [20, 30, 60, 80]
// Shorthand
let arr2 = [...arr1, 60, 80];
// [20, 30, 60, 80]
19. Deep cloning of multi-level object
To deep-clone a multi-level object, we can iterate through each property and check if the current property contains an object. If yes, then do a recursive call to the same function by passing the current property value (i.e. the nested object).
We can also do it by using JSON.stringify()
and JSON.parse()
if our object doesn't contain functions, undefined, NaN, or Date as values.
If we have a single-level object i.e no nested object present, then we can deep clone using the spread operator also.
let obj = {x: 20, y: {z: 30}};
// Longhand
const makeDeepClone = (obj) => {
let newObject = {};
Object.keys(obj).map(key => {
if(typeof obj[key] === 'object'){
newObject[key] = makeDeepClone(obj[key]);
} else {
newObject[key] = obj[key];
}
});
return newObject;
}
const cloneObj = makeDeepClone(obj);
// Shorthand
const cloneObj = JSON.parse(JSON.stringify(obj));
// Shorthand for single level object
let obj = {x: 20, y: 'hello'};
const cloneObj = {...obj};
Improvement from comment: The shorthand technique (
JSON.parse(JSON.stringify(obj))
) doesn’t work if your object property containsfunction
,undefined
orNaN
as value. Because when you JSON.stringify the object, the property containingfunction
,undefined
orNaN
as value gets removed from the object.So use
JSON.parse(JSON.stringify(obj))
when your object contains only strings and numbers.
Reference: JSON.parse() and JSON.stringify()
20. Get a character from a string
let str = 'jscurious.com';
// Longhand
str.charAt(2); // c
// Shorthand
str[2]; // c
21. Flatten nested arrays
We can use the Array.flat(depth)
method to flatten nested arrays.
const arr = [1, [2, 3, [4, [5]], 6], 7];
console.log(arr.flat(1)); // [1, 2, 3, [4, [5]], 6, 7]
console.log(arr.flat(2)); // [1, 2, 3, 4, [5], 6, 7]
If you are not sure about the depth, use flat(Infinity)
to flatten the array of any depth.
console.log(arr.flat(Infinity)); // [1, 2, 3, 4, 5, 6, 7]
Note: Some of these shorthand techniques may not seem relevant to use in the project but it’s not bad to know some extra techniques. Happy coding!
You may also like
- Send push notifications with the Notification API in JavaScript
- Play audio with HTMLAudioElement API in JavaScript
- Map in JavaScript and when its a better choice than Object
- JavaScript Set object to store unique values
- Generator functions in JavaScript
- A brief guide to Promises in JavaScript
- JavaScript Fetch API to make HTTP requests
- Different ways to check if a property exists in an object in JavaScript
- The Vibration API in JavaScript
- The URLSearchParams API in JavaScript
Thanks for your time ☺️
For more Web development blogs, Please visit jscurious.com
Amitav Mishra