DEV Community

Shubhra Agarwal
Shubhra Agarwal

Posted on

Some cool JavaScript Shorthand that will make your code cleaner than your peer's

Here are 7 JavaScript shorthands that you as a JavaScript developer should know because who doesn't like shorter and cleaner code ¯_(ツ)_/¯

Convert string to number

Normally we use the parseInt() to do this. But, you can do this using the unary operator +. Sick right?
image

You can also do this by just adding the unary operator to an empty string
image

The ternary operator

I'm pretty sure all of you must be aware about this but what's the harm in sharing it again.

image

The short circuit

Ever wanted to check for a condition and output something only if the condition was true? Were you also using && like me? Well, not anymore, I present to you the short circuit.
image
image

Flattening an array

A lot of people use various methods to flatten an array like filter(), concat etc. But using the flat() method can get the job done quicker and better.
image

Merging arrays

Merging of arrays is one of the tasks that we need to do in our day to day coding. Be it the data from an API or whatever. Using the spread operator can get this job done in no time.
image

Cloning Arrays

Just like merging, spread operator comes in handy even when you want to clone an array

image

The shorthand of for loops

We all have been writing for loops the C++ way up until now, but now it's time to do it the modern way. image

TL;DR

  1. Convert string to number
  2. Ternary Operator
  3. Short Circuit
  4. Flattening an array
  5. Merging arrays
  6. Cloning Arrays
  7. The shorthand for loop

Top comments (25)

Collapse
 
elmuerte profile image
Michiel Hendriks

who doesn't like shorter [...] code

The next person who has to look at it. Shorter is only better when it makes the code simpler and better to understand.

Collapse
 
tbroyer profile image
Thomas Broyer

+1, I'm not sure the author has the same definition of cleaner than me.

Collapse
 
vitiok78 profile image
Victor Cozhuhari

I think if you are reviewing the code and stopping at this shorthand for a few seconds to figure out what it is doing then it is already bad. Because if you'll debug such a shorthand fest in the future you will curse that "smart" developer...

Collapse
 
vitiok78 profile image
Victor Cozhuhari

Nested ternary operator is a pure evil. Just. Don't. Use. It. Never.
Thank me later.

Collapse
 
haaxor1689 profile image
Maroš Beťko

I've never seen any problem at all with using nested ternary operators especially in React component code. Just set up your eslint right and it will consistently format it for you. With nested ternaries you have 2 cases:

  1. Tree-like nesting:
cond1
  ? cond2 // if
    ? opt1 // if
    : opt2
  : opt3
Enter fullscreen mode Exit fullscreen mode
  1. chained nesting:
cond1 // if
  ? opt1
  : cond2 // else if
  ? opt2
  : opt3 // else
Enter fullscreen mode Exit fullscreen mode

It's not that complicated.

Collapse
 
vitiok78 profile image
Victor Cozhuhari

It's even worse because it's tricky and uncommon.
"If" "else" are more straightforward.
But I consider using "else" as a bad practice because it complicates the logic in readability context.
Break this logic into the smaller functions or methods and use early return inside those functions instead of "else". And the code will be clean, readable and easily refactored. The person who will work with it later will thank you a lot.

Thread Thread
 
haaxor1689 profile image
Maroš Beťko

Saying tricky and uncommon is pretty subjective. From my subjective point of view in codebases of our projects at work it's nothing unusual to find ternary operators and no one is complaining.
As I've said it's especially useful in React code since you can't write if statements there. Let's say you want to conditionally show some data that is fetched asynchronously.

<div>
    {response.isLoading ? (
        <div>Loading...</div>
    ) : response.isError ? (
        <div>{response.error.message}</div>
    ) : (
        <div>{repsonse.data}</div>
    )}
</div>
Enter fullscreen mode Exit fullscreen mode

And this is pretty common example I would say. Other option would be to use && operators.

<div>
    {response.isLoading &&
        <div>Loading...</div>}
    {response.isError &&
        <div>{response.error.message}</div>}
    {!response.isLoading && !response.isError &&
        <div>{repsonse.data}</div>}
</div>
Enter fullscreen mode Exit fullscreen mode

And another option would be to make some helper methods or nested component so you can use the if/else statements there.

Personally, I prefer the first option. It's the most scale-able since if you want to add a condition you don't have to update the last one and it's the least overhead.

Thread Thread
 
vitiok78 profile image
Victor Cozhuhari • Edited

It is exactly one of the many reasons why I prefer Vue over React. That ugly JSX mess that mixes JavaScript logic and kinda HTML markup is awful. Separate template engine is always better. Other languages figured it out long time ago. Even in PHP they prefer to use Twig rather than mixed mess.

Vue:

<div>
    <div v-if="response.isLoading">Loading...</div>
    <div v-else-if="response.isError">{{ response.error.message }}</div>
    <div v-else>{{ repsonse.data }}</div>
</div>
Enter fullscreen mode Exit fullscreen mode

P.S. BTW else-if and else look natural and clean in template but they are bad inside JavaScript code at the same time

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️

JSX is an abomination - makes me want to vomit every time I see it 🤮

Collapse
 
shubhracodes profile image
Shubhra Agarwal

Wow, That is a beautiful explanation.

Thanks for explaining it so easily

Collapse
 
drewerd15 profile image
drewerd15

Agreed nested ternary just looks gross. I don't even really like multi line ternerys. Use a switch or an if else

Collapse
 
shahilalit profile image
ShahiLalit • Edited

Totally agree here, please don't use ternary operator if it's going to have 2 levels. Next de will have to give more time to understand it. Just use, if else.. no harm in that..

But that being said, a great article bro. Few shortcodes are really helpful.👍

Collapse
 
shubhracodes profile image
Shubhra Agarwal

Thanks

Collapse
 
whynotgithub profile image
Why-Not-GitHub

Agree!

Collapse
 
haaxor1689 profile image
Maroš Beťko

Almost all of these I use pretty regularly and feel like every modern codebase should use them.
Here are some additional shorthands I use:

Range 1,2,3...n:

[...Array(n).keys()]
Enter fullscreen mode Exit fullscreen mode

Remove key from object:

const { key: _, obj } = object;
Enter fullscreen mode Exit fullscreen mode

Swap array items:

[arr[x], arr[y]] = [arr[y], arr[x]]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited
[...Array(n).keys()]
Enter fullscreen mode Exit fullscreen mode

Gives you a range 0 to n-1. For a range 1 to n, you could use:

// This (much faster)...
Array.from({length:n},(_,i)=>i+1)

// Or maybe this (shorter but slower)...
[...Array(n).keys()].map(i=>i+1)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shubhracodes profile image
Shubhra Agarwal

Thank you for sharing this. I'm saving this comment for future reference

Collapse
 
matt profile image
Matt seymour

I cannot help but think the author has confused "clean code" with shortest code.

If anyone on my team wrote the "tenary example" I would give them a serious talking too. Why?
Code is generally written once and read many times. The focus should never be on the shortest code you can write but instead on the most readable code you can write. Even if that means the code is 20% longer than a shorter solution.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

'Readable' is purely subjective - depends upon the "reading level" of the reader. That said, nested conditional operators are not great

Collapse
 
midblep profile image
Mid

The short circuit is a very useful shorthand that has many practical uses and isn't too hard to read. Thanks for teaching me it, I use this stuff so much.

Collapse
 
shubhracodes profile image
Shubhra Agarwal

I'm glad you liked it🧡

Collapse
 
naru profile image
Anton Narusberg

Shorter is not always easier to read. For example, nested ternaries are always a fun puzzle for the next person.

Collapse
 
micahlt profile image
Micah Lindley

Some of these are really good! Thanks for sharing!

Collapse
 
shubhracodes profile image
Shubhra Agarwal

Thanks :)

I'm glad you liked it

Collapse
 
hellobexnewton profile image
Bex Newton

This is great. Thanks for sharing!