Useful JavaScript Shorthands I Wish I Knew Sooner

The most commonly used shorthands for reducing lines of code in JavaScript.

Angela Wong
JavaScript in Plain English

--

JavaScript is a beautiful language that has an array of useful shorthand alternatives for common code concepts. They are good for reducing lines of code and improving code readability. In this article, I have summarised the most commonly used shorthands and included the longhand to guide you through.

  1. Using for loops
const fruits = ['apple', 'peach', 'banana'];
for (let i=0; i < fruits.length; i++) {};
// shorthand
for(let fruit of fruits)
// if you want to access index only
for(let fruit in fruits)

2. Math Shorthand

Math.floor(4.9) // shorthand
~~4.9
Math.pow(2,3);// shorthand
2**3

3. Find function

const members = [
{gender: 'M', name: 'John'},
{gender: 'M', name: 'Tim'},
{gender: 'F', name: 'Jenny'},
{gender: 'F', name: 'Alice'}
]
findTim = (name) => {
for(let member of members) {
if(member.name === name && member.gender === 'M') {
return member.name
}
// shorthand
member = members.find(member => member.gender === 'M' && member.name === 'Tim');

4. Join & clone arrays using spread operators

const oddNumbers = [3,5,7]
const numbers = [2,4,6].concat(oddNumbers);
// shorthand
const numbers = [2,4,6,...oddNumbers];
const array = [1,2,3];
const arrayClone = array.slice();
//shorthand
const arrayClone = [...array];

5. String to number

const num1 = parseInt("100");
const num1 = parseFloat("100");
// shorthand
const num1 = +"100";

6. Destructuring

const id = this.props.id;
const title = this.props.title;
const author = this.props.author;
// shorthand
const {id, title, author} = this.props;

7. Template Literals

const db = "http://" + host + ":" + port + "/" + database;// shorthand
const db = `http://${host}:${port}/${database}`;

8. Declaring variables

let a = 3;
let b = 3;
let c = 3;
//shorthand
let a=3, b=3, c = 3;

9. Ternary Operator

It is a shorthand for the traditional if…else statement.

if (condition) {
return "true"
} else {
return "false"
}
// shorthand
let condition = true;
let result = condition ? 'true' : 'false';

10. Nullish coalescing operator

It is used to assign default value to a variable, the operator only uses the default value when intended value is null.

// case 1 
let value = null;
let finalValue = value ?? 'default value';
console.log(finalValue); // 'default value'// case 2
let value = 'intended value';
let finalValue = value ?? 'default value';
console.log(finalValue); // 'intended value'

Conclusion

I hope the above explanation helps you in understanding codes. However, it has to be cautious when using shorthands, as what matters the most is not writing shortcodes, but writing clean and understandable codes that other developers can read easily!

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord. Interested in Growth Hacking? Check out Circuit.

--

--