11 JavaScript and TypeScript Shorthands You Should Know

Some very useful (and sometimes cryptic) JS/TS shorthands to use or at least understand when reading others’ code.

Fernando Doglio
Bits and Pieces
Published in
9 min readAug 24, 2020

--

There is a very fine line between writing clean and efficient code and writing code that only you can read. And the worst part is, that line is not universal, some people would draw it much further than others so when it comes to deciding if a piece of code is legible enough for everyone we tend to stay away from using many shorthands such as ternary operators, on-line arrow functions and whatnot.

But the ugly truth is: sometimes, those shorthands come in very handy and are easy enough that anyone who’s interested enough in reading our code can and will understand them.

So in this article, I want to cover some very useful (and sometimes cryptic) shorthands that you can find both in JavaScript and in TypeScript so you can either use them yourself or at least, have know them in case the person who’s code you’re reading has used them.

1. The Nullish Coalescing Operator

With a name like that, it’s hard to believe it’s not one of the most popular operators in the language, am I right?

The point of this operator, is to allow you to return a value if the evaluated expression is either null or undefined which is not exactly what the name implies, but oh well. Here is how you’d use it:

Pretty much like the || operator, the logic behind it is the same: if the left side of the expression is evaluated to null or undefined it’ll return the right side, otherwise, it’ll return the left side. So for generic default values where you can have any type of value assigned and are looking to make sure you don’t have to deal with an undefined or null then this is the way to go.

2. Logical nullish assignment

This one is an extension of the previous one, you can use the ??= operator to do both at the same time: check for a nullish coalscing value and assign it if it is one.

Let’s take another crack at the same code sample:

The assignment operator allows us to check for the value of variable2 and if it evaluates to either null or undefined then the assignment will go through, otherwise it will never happen.

Warning: this syntax can be confusing to others that aren’t familiar with this operator, so if you’re using it you might as well leave a one-line comment explaining what’s happening.

3. TypeScript’s constructor shorthand

This one is specific to TypeScript, os if you’re a JavaScript purist, your missing out! (nah, just kidding, but you can’t do this with plain JS).

You know how when defining a class you usually list all properties with their corresponding visibility and then inside the constructor, you assign their values? Well, for those cases where your constructor is very simple and you’re just assigning values received as parameters, there is a shorthand for you.

Let me show you:

This one is definitely a time-saver, specially if you have a class with a lot of properties.

Essentially what you want to make sure, is that you don’t forget to add that {} right after the constructor, since that’s the body of the function. And that’s it, the rest is done by the compiler, understanding what we’re trying to achieve, it’ll turn both versions of the code into the same JavaScript snippet.

Tip: Share your reusable modules/components between projects using Bit (Github). Bit makes it simple to share, document and organize independent components from any project.

Use it to maximize code reuse, collaborate on independent components and build apps that scale.

Bit supports Node, TypeScript, React, Vue, Angular, and more.

4. The ternary operator

This one is relatively easy to read and it tends to be used instead of one-line IF..ELSE statements, because it removes a lot of unneeded characters and turns four lines into one.

You can see the structure of the ternary operator essentially has the boolean expression first, then a sort of “return” statement for the case when said expression is true and a “return” statement for the case when the expression is false. Although best used on the right side of an assignment (as in the example), it can also be used alone as a way to execute a function call depending on the value of a boolean expression.

Notice that the format is the same, the issue here is that if in the future you need to expand one of the sections here (either for when the expression is true or false), you’ll have to turn it into a full-blown IF..ELSE statement.

5. Take advantage of OR’s lazy evaluation

In JavaScript (and thus TypeScript as well) the OR logical operator follows a lazy evaluation model, meaning, it’ll return the first expression that returns true and it won’t keep checking for the rest.

This means that if you have the following IF statement, only the first two expressions will be evaluated:

if( expression1 || expression2 || expression3 || expression4)

Assuming expression1 is falsy (i.e it returns a value that is evaluated to false ) and expression2 is truthy (i.e it returns a value that is evaluated to true ) then the evaluation will stop there.

We can take advantage of this lazy evaluation, and instead of using it inside the IF statement, we can use it as part of an assignment in order to provide a default value in case your expression fails or is undefined :

The example above shows how you can use the OR operator to set a default value for the second parameter of the function. Now, if you look closely though, you’ll find a small problem with this approach: if variable2 has the value of 0 or an empty string, you’ll be setting the default value on var2 because they both evaluate to false.

So if your use case allows for falsy values to be valid values as well, then you might want to look at a lesser known operand called the “Nullish coalescing operator”.

6. The double bitwise NOT operator

Bitwise operators are the ones we tend to stay away of, because honestly, who needs to think about bits nowadays right? The thing is, however, that because of the way they work directly on the bits of your numbers, they perform their operations a lot faster than normal method calls.

In this case, the bitwise NOT operator (i.e ~) will grab your numbers, it’ll turn them into a 32bits integer (discarding any extra bits) and then it’ll invert all their bits essentially turning any integer of value x into -(x+1) . Why do we care the about this operator? Because if we use it twice on the same value, we get the same result as the Math.floor method.

Notice the double ~ on the last line, although it might look weird, if you’re having to deal with turning multiple floating-point numbers into integers, this might be a good shorthand for you.

7. Object property assignment

ES6 simplified the process of object creation when you’re assigning values to your properties. If the values are assigned to variables named exactly like your object’s properties, then you no longer have to repeat the names like you had to before:

As you can see, the new way is definitely shorter and easier to write whilst at the same time, not harder to read (unlike other shorthand tips shown in this article).

8. Implicit return from arrow functions

Did you know arrow functions that are only one line long, also return the result from that line of code?

Essentially, this tip allows you to save a redundant return statement. A very commonplace to find these type of shorthand being used is on array methods, such as filter or map, like this:

This one doesn’t necesarily add complexity to your code, and it’s a nice way of cleaning up your syntax a bit removing unwanted spaces and lines. Of course, the downside here is that if you ever need to add extra logic to those lines, you’ll have to add back the curly brackets.

The only caveat here is that whatever you attempt to execute on your one-line function needs to be an expression (i.e something you can return), otherwise it won’t work. For instance, you can’t have a one-liner like this:

const m = _ => if(2) console.log("true")  else console.log("false")

And you’ll see another example of a one-liner that requires curly brackets in the next example, so let’s move on.

9. Default function parameters

Thanks to ES6, you can now specify default values on function parameters. On the previous version of JavaScript this wasn’t possible, thus you’d have to resort to using something like OR’s lazy evaluation.

But now it’s as easy as writing:

Simple enough isn’t it? Well, it actually get’s a little more interesting, since the value can be anything, including a function call which will get executed if you don’t overwrite it with your own value, thus allowing you to also implement a mandatory function parameter pattern really easy. Check it out:

Like I said, the one-liner mandatory needs the curly brackets because it’s using throw which is a statment instead of an expression. But you still get the cool mandatory parameter behavior with very little effort.

10. Casting any value to a boolean with !!

In a similar note to the double bitwise NOT operator, you can use the double logical NOT operator to cast any value to a boolean.

!!23 // TRUE
!!"" // FALSE
!!0 // FALSE
!!{} // TRUE

The single logical NOT will already do that for you, it’ll cast the value to apply it to into a boolean and then it’ll negate it, so the second logical NOT will take care of negating it againg, thus returning it to it’s original meaning, while keeping it as a boolean type.

This shorthand is useful in those cases where you either have to be sure you’re assigning an actual boolean (such as a TypeScript variable of type boolean ) or when doing a strict comparison against either true or false (with ===).

11. Destructuring and spread operators

There is a lot to say about both topics, after all used correctly, they can produce very interesting results. But for this article, let me quickly show you how you can take advantage of both to simplify some tasks.

Destructuring an object into multiple variables

Have you ever had to assign a bunch of different object properties to individual variables? This is actually quite common for example if you need to deal with those values individually (by modifying them for example) without affecting the original object.

Destructuring can help you do that in a single line of code:

This syntax can also be seen as part of import statements if you’ve used TypeScript before, because it allows you to individually import some of the methods libraries export without having to clug the namespace with a lot of unwanted functions.

const { get } from 'lodash'

For example, that line above allows you to only add the get method from the lodash library to your namespace without adding the rest of the library, which has A LOT more methods inside.

Spreading to merge

Using the spread operator, you can simplify the task of merging both, arrays and objects into a single line of code, without having to call any extra methods:

Notice that merging objects like this will cause properties to be overwritten if they share the same name. The same however won’t happen with arrays, repeated values will be added, you’ll have to resort to using a Set if you want to avoid that as well.

Combining both

You can even combine destructuring and the spread operator to achieve interesting results, such as removing the first element of an array and leaving the rest intact (i.e the common head and tail example with lists you can find in Python and other languages). Or even extract some properties from an object and leave the rest intact, like this:

Notice that the spread operator on the left side of the assignment has to be used as the last item. You can’t first use the spread and then add individual variables like this:

const [...values, lastItem] = [1,2,3,4]

The above example will fail.

Conclusion

There are a lot more shorthands around but remember that the more code you save, the less readable it becomes to others who’re not used to those shorthands. This is not about minifying your code, or implicitly assuming that the fewer lines of code will result in a more performant code. This is just about removing redundant or unnecessary constructs from your syntax in order to simplify the reading task.

So try to keep a healthy balance of shorthands and readable code in order to keep everyone happy (remember that you’re not the only one reading your code!).

Have I missed your favorite shorthand? Leave it down below and share it with the community!

Learn More

--

--

I write about technology, freelancing and more. Check out my FREE newsletter if you’re into Software Development: https://fernandodoglio.substack.com/