20 JavaScript Shorthand Techniques that will save your time

Amitav Mishra
Nov 1 · 6 min read
Image for post
Image for post
Posted in jscurious.com

The shorthand techniques of any programming language help you to write more clean and optimized code and lets you achieve your goal with less coding. Let’s discuss some of the shorthand techniques 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

//Longhand 
let a, b, c;
a = 5;
b = 8;
c = 12;
//Shorthand
let [a, b, c] = [5, 8, 12];

3. The Ternary operator

//Longhand 
let marks = 26;
let result;
if(marks >= 30){
result = 'Pass';
}else{
result = 'Fail';
}
//Shorthand
let result = marks >= 30 ? 'Pass' : 'Fail';

4. Assigning default value

//Longhand 
let imagePath;
let path = getImagePath();
if(path !== null && path !== undefined && path !== '') {
imagePath = path;
} else {
imagePath = 'default.jpg';
}

//Shorthand
let imagePath = getImagePath() || 'default.jpg';

5. AND(&&) Short circuit evaluation

//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

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

//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

//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

//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

let firstname = 'Amitav'; 
let lastname = 'Mishra';
//Longhand
let obj = {firstname: firstname, lastname: lastname};

//Shorthand
let obj = {firstname, lastname};

12. String into a Number

//Longhand 
let total = parseInt('453');
let average = parseFloat('42.6');

//Shorthand
let total = +'453';
let average = +'42.6';

13. Repeat a string for multiple times

//Longhand 
let str = '';
for(let i = 0; i < 5; i ++) {
str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello Hello

// Shorthand
'Hello '.repeat(5);

Tip: Want to apologize to someone by sending 100 times “sorry”? Try it with repeat() method. If you want to repeat each string in a new line, then add \n to the string.

'sorry\n'.repeat(100);

14. Exponent Power

//Longhand 
const power = Math.pow(4, 3); // 64

// Shorthand
const power = 4**3; // 64

15. Double NOT bitwise operator (~~)

//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 number in array

But using 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

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

We can also do it by using JSON.stringify() and JSON.parse() if our object doesn't contains functions, undefined, NaN or Date as values.

If we have single level object i.e no nested object present, then we can deep clone using 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 contains function, undefined or NaN as value. Because when you JSON.stringify the object, the property containing function, undefined or NaN 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 character from string

let str = 'jscurious.com'; //Longhand 
str.charAt(2); // c

//Shorthand
str[2]; // c

Some of these shorthand techniques may not seems relevant to use in project but it’s not bad to know some extra techniques. Happy coding!

Thanks for your time☺️
For more Web development blogs, Please visit jscurious.com

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Amitav Mishra

Written by

A front end web developer who loves to write blogs on JavaScript, Angular, React, HTML, CSS etc. Find them all on jscurious.com

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Amitav Mishra

Written by

A front end web developer who loves to write blogs on JavaScript, Angular, React, HTML, CSS etc. Find them all on jscurious.com

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store