10 JS Shorthand Techniques

Antonija Dimoska
Codeart
Published in
7 min readOct 5, 2020

If you are reading this, it means you have used JavaScript at least once in your life. This post is for beginners and seniors as well, since even after 3 years of experience (at the time of writing this post) some of the shorthand techniques I found were new to me too.

So let’s get started, and hopefully some of these techniques will help you in better organizing your code, since we all love organized code, don’t we?

1. Ternary Operator

This one is my absolute favorite. Before, if a variable depended on a condition, you would write something like this:

const pet = 'dog';
let sound;
if ( pet === 'dog') {
sound = 'woof';
} else {
sound = 'meow';
}

This can be simplified in the following:

const pet = 'dog';
let sound = (pet === 'dog') ? 'woof' : 'meow';

This has the same functionality as the longhand above. At the moment of initialization it checks whether the pet is a dog, and assigns the corresponding value. So, from 7 lines of code, we managed to shrink it to two. Let’s see what else we can do:

2. If presence/absence

This one is also one of my most used ones, but it can be tricky. First let’s see how you would check if a variable is absent or not.

let test = 'AA';if (typeof test !== 'undefined' && test !== '' && test !== null && test !== 0 && test !== false) {
console.log('The variable test is defined and not empty and not null and not false');
}

These are all the conditions you have to check to know if the variable is defined, is not empty, is not null, is different than 0 and is not false.

The shorthand of this is simply:

let test = 'AA'
if (test) {
console.log('The variable test is defined and not empty and not null and not false');
}

To check if the variable is absent:

let test;
if (!test) {
console.log('The variable test is undefined or empty or null or false');
}

The tricky part of this, is to know whether you are checking for truthy value or if the variable needs to be equal to the boolean true.

Check the following examples:

let example = true;
if (example === true) {
console.log('It is true');
} else {
console.log('It is false');
}
if (example) {
console.log('it is true');
} else {
console.log('It is false');
}

Both of these will print ‘It is true’.

But, if we change the value of example:

let example = 'testing';
if (example === true) {
console.log('It is true');
} else {
console.log('It is false');
}
if (example) {
console.log('It is true');
} else {
console.log('It is false'}
}

The first example will print ‘It is false’, and the second example will print ‘It is true’.

This happens because if you omit any operators, the if condition will be true if it has a truthy value, meaning if it is a string, or text containing false, or an empty array, or empty object, or empty function.

On the other hand, if you use the first example, then the if condition will be true only if the value of the variable example is a boolean true.

3. Variables in bulk

If you have ever done a bigger script in JS, you know how many variables you need to declare and how much space it can take.

Longhand:

let i = 0;
let j = 0;
let counter = 0;
let message = 'Hello there';
let isFound = false;
let isOpen = true;
let text;

Now, these are just a few. Imagine if you have at least ten more. It takes up a lot of space. Luckily, there is a shorthand for this:

let i = 0, j = 0, counter = 0, message = 'Hello there', isFound = false, isOpen = true, text;

From many lines, you have shrunk the code to one line. Now, in my experience, if you have many variables, it can quickly become more annoying than helpful to write them in one line, so what I do, is divide them in groups.

let i = 0, j = 0, counter = 0; // counters
let message = 'Hello there', text; // strings
let isFound = false, isOpen = true; // booleans

This way, it might be longer than one line, but for me, it is more organized. Use whichever works better for you.

4. Decimal Numbers

Did you know that there is a fancy and short way of writing long numbers? I didn’t but I’ll be using it from now on, for sure. For instance, if you have a for loop like this:

for (let i = 0; i < 1000000; i++) { }

You can write it like this:

for (let i = 0; i < 1e6; i++) {}

So the format is xey

x — represents the first number
e — indicates that zeroes follow x
y — represent the number of zeroes

So:

1e1 === 10
1e2 === 100
1e3 === 1000
.
.
.
1e9 === 1000000000
2e1 === 20
2e2 === 200
.
.
2e8 === 200000000
11e2 === 1100

And so on. You get the gist.

5. Template Literals*

One of the most annoying things for me, is if I need to print some text which contains more variables, like:

let text = 'Hello '+ name + 'from '+ country +'.'

Especially if the text turns out to be in multilines.

let multilineText = 'Hello '+ name + 'from '+ country +'.\n\t'
+ 'You have selected '+ number + '' + item + 'at the price of '+ price + '.'

This doesn’t look clean. It looks overstuffed and confusing. But, here comes template literals to the rescue, only with the use of backtick(`) and ${}.

So these confusing strings, can be written like:

let text = `Hello ${name} from ${country}.`;
let multilineText = `Hello ${name} from ${country}. You have selected ${number} ${item} at the price of ${price}`;

It looks way better and cleaner, right?

6. Object Property*

Here’s the old way of declaring an object in JS.

let name = 'Katniss';
let surname = 'Everdeen';
let home = 'District 12';
let contestant = {
name: name,
surname: surname,
home: home
}

The shorthand for this is:

let contestant = { name, surname, home }

This works only if the key name is the same as the variable name assigned to it.

7. For Loop Shorthand

There is another useful js shorthand. Let’s see how you would write a for loop that iterates over object items.

const heroes= ['Iron Man','Thor','Hulk','Black Widow','Scarlet Witch','Dr Strange','Spiderman'];for(let i = 0; i < heroes.length; i++) {
console.log(heroes[i]);
}

This will print:

/**
Iron Man
Thor
Hulk
Black Widow
Scarlet Witch
Dr Strange
Spiderman
*/

Now, the shorthand of this is the following:

for(let hero of heroes) {
console.log(hero);
}

It will print the same. If you need the index, then it will look like this:

for(let index in heroes) {
console.log(index);
}

It will print

/**
0
1
2
3
4
5
6
*/

8. String to Number

If you wanted to convert string to number, you would probably do this:

const num1 = parseInt('10');
const num2 = parseFloat('10.01')

The shorthand of this is:

const num1 = +"10";
const num2 = +"10.01";

num1 will be converted to integer, and num2 will be converted to float.

9. Destructuring Assignment*

This one is a really useful one that makes the code cleaner. What destructuring means, is being able to unpack values from arrays, or properties from objects, into distinct variables.

How would we normally do it:

const student = {
name: 'Harry',
surname: 'Potter',
school: 'Hogwarts',
house: 'Gryffindor'
}
const name = student.name;
const surname = student.surname;
const school = student.school;
const house = student.house;

If we use destructuring assignment, the above can be written like:

const {name, surname, school, house} = student;console.log(name) // Harry
console.log(surname) // Potter
console.log(school) // Hogwarts
console.log(house) // Gryffindor

Same can be applied to arrays:

let a,b,c;
[a,b,…c]= [1,2,3,4,5,6,7,8,9]
console.log(a) // 1
console.log(b) // 2
console.log(c) // [3,4,5,6,7,8,9]

10. The Spread Operator & Rest Parameter (…)*

Spread operator makes it easier to work with arrays. Look at the examples:

let num1 = [1,2,3]
let num2 = [4,5,6]
let final;
final = num1.concat(num2);

With the spread operator, this becomes:

final = […num1,…num2] //1,2,3,4,5,6

Other examples:

final2 = […num2, …num1] // 4,5,6,1,2,3final3 = [1, 2, …num2, 7,8 ] // 1,2,4,5,6,7,8

The rest parameter has the same syntax as the spread operator (…). It allows us to represent indefinite number as arguments as an array.

function restExample(a, b, ...more) {
console.log('a = ', a);
console.log('b = ', b);
console.log('more = ', more);
}
restExample('Testing','for','rest','parameter','here');
// Output:
// a = Testing
// b = for
// more = ['rest','parameter','here']

Note: Only the last parameter can be “rest parameter”.

These are just a few of the JavaScript Shorthand Techniques. There are many more, but for starters, these are the ones I use the most.

Feel free to tell me which ones you use the most. And keep on writing clean, readable and organised code.

“Indeed, the ratio of time spent reading versus writing is well over 10 to 1. We are constantly reading old code as part of the effort to write new code. …[Therefore,] making it easy to read makes it easier to write.”
Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

Note: The ones marked with * are not supported in Internet Explorer. If you need to have support for Internet Explorer you can use a transpiler (ex. Babel) which will transform your code for IE and older browser versions.

--

--