DEV Community

Cover image for 7 Shorthand Optimization Tricks every JavaScript Developer Should Know 😎

7 Shorthand Optimization Tricks every JavaScript Developer Should Know 😎

Tapajyoti Bose on October 30, 2022

Every language has its own quirks and JavaScript, the most used programming language, is no exception. This article will cover a plethora of JavaSc...
Collapse
 
exodes profile image
Exo Des

I think the the fallback values need some correction. Using logical OR || doesn’t give you the value you want if the value is [] or 0. The better solution would be using the nullish coalescence ?? where if only use the fallback values when the defined value is null or undefined.

Collapse
 
the_riz profile image
Rich Winter

☝️

Collapse
 
seagull29 profile image
Erian

☝️

Thread Thread
 
0x04 profile image
Oliver Kühn

☝️

Thread Thread
 
birkankervan profile image
Emre Birkan Kervan

☝️

Thread Thread
 
pogpog profile image
pogpog

☝️

Thread Thread
 
gabrandalisse profile image
Gabriel Andres

☝️

Collapse
 
moopet profile image
Ben Sinclair

In point 1, everything's fine, but you make the "long hand" version look longer by adding a redundant if.. else. This would be a better comparison:

// Long-hand
const isVowel = (letter) => {
  return (
    letter === "a" ||
    letter === "e" ||
    letter === "i" ||
    letter === "o" ||
    letter === "u"
  );
};
Enter fullscreen mode Exit fullscreen mode

In point 4 I would recommend against nesting ternaries because you quickly get an unreadable mess of code, especially when the lines contain long strings which wrap in your editor.

Collapse
 
posandu profile image
Posandu

Nice post!

The 5th can be changed as follows

function f1() {
    // ...
}
function f2() {
    // ...
}

conditon ? f1() : f2();
Enter fullscreen mode Exit fullscreen mode

And the 6th can be improved by using Arrays

const dayNumber = new Date().getDay();

const days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
];
// Or
const days = `Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday`.split(
    ","
);

const day = days[dateNumber];
Enter fullscreen mode Exit fullscreen mode
Collapse
 
frankwisniewski profile image
Frank Wisniewski
    const weekday = new Intl.DateTimeFormat('de-DE',{weekday: 'long'}).format(new Date())
Enter fullscreen mode Exit fullscreen mode
Collapse
 
the_riz profile image
Rich Winter

Suggestion is a bit of a "premature optimization" - you just created a string " Sunday" instead of "Sunday"

With something like this, sometimes the longer way is just easier for the next guy to read. Especially when that next guy is you.

Collapse
 
ooling profile image
Sam oo Líng
(condition ? f1 : f2)();
Enter fullscreen mode Exit fullscreen mode

Is a new thing for me, but why'd you suggest

conditon ? f1() : f2();
Enter fullscreen mode Exit fullscreen mode

instead?

Collapse
 
posandu profile image
Posandu

If you need to add different arguments to each function call. You can't do it from the 1st method.

Thread Thread
 
ooling profile image
Sam oo Líng

ah so that's why..

Thread Thread
 
gorissomanuchi profile image
Gorisso-manuchi

hi my friend

Thread Thread
 
ooling profile image
Sam oo Líng

hello too

Collapse
 
spidermath profile image
Undefined Dev • Edited

Good job with the article, but I do have some things to say:
For #7, I'd rather go with the nullish coalescing operator(??) than ||...
And for #4, wouldn't it be a good idea to talk about why someone shouldn't use ternary operators too much as well, i.e., nested ternary operators can be a nightmare for readability, and recommending against it would be good for people who are learning about ternary operators.

Collapse
 
ignore_you profile image
Alex

Nested ternary would never pass my code review. IMO, one-liner is not an optimization if it affects readability.

Even though your #1 example is more general, this specific case can be shortened:

const isVowel = (letter) =>
  'aeiou'.indexOf(letter) > -1
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nishithsavla profile image
Nishith Savla

I resist from using indexOf as you can instead use includes

'aeiou'.includes(letter)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rolandixor profile image
Roland Taylor

Some great tips here! Thanks for sharing!

Collapse
 
stefanthespider profile image
StefanTheSpider

I miss the unicorn 🥲

Collapse
 
sharpweb profile image
WebSharp

thanks for sharing this stuff

Collapse
 
madza profile image
Madza

Some great tips right here, thanks 👍💯

Collapse
 
timhuang profile image
Timothy Huang

Interesting and useful, thanks for sharing.

Collapse
 
renzoov profile image
Renzo Osorio

Good article, thanks

Collapse
 
jayanika profile image
Jayanika Chandrapriya

Nice post 🤩

Collapse
 
wilmela profile image
Wilmela

Cool

Collapse
 
rafaelcg profile image
Rafael Corrêa Gomes • Edited

Great tips; Thanks for sharing it!

Collapse
 
baltaguirre profile image
Baltasar Aguirre

Great post!! Thanks!!

Collapse
 
fayomihorace profile image
Horace FAYOMI

This is Great

Collapse
 
lexlohr profile image
Alex Lohr

Most of your solutions have worse performance and sometimes different functionality. For example, a classic for-loop will execute even for the undefined items in sparse arrays; neither for-of nor array.prototype.forEach will do that.

Also, your function call shorthand requires that you are careful with semicolons, because otherwise, you might run into a TypeError: undefined is not a function when the previous statement also ended with brackets.

Collapse
 
jckr profile image
Jerome Cukier

I don't think the includes approach can be faster than multiple ors for such a small list of values.
Array.prototype.includes, as Array.prototype.indexOf, is going to have a tiny overhead over just checking if the value is equal to the first item, then the next, then the next, etc.
I'm also not sure it is more legible.

If the use case is to check if a string contains vowels, a regular expression is going to be both much faster and more concise. ie myString.search(/[aeiou]/)

Collapse
 
almostconverge profile image
Peter Ellis

If I can add a personal request: yes, ternary operators are cool and useful but please, please, please try to avoid using nested ternary operators like in this example.

Don't get me wrong, they work just fine but they are relatively difficult to read and they don't auto-format very well.

(You might say It's not that much harder to read, and I don't disagree much, but it's always useful to remember that code is only written once but read many times, so any time saved on writing that makes reading harder is likely to end up costing you more overall.)

Collapse
 
vidipghosh profile image
Vidip Ghosh

Very useful.

Collapse
 
uttam_py profile image
Uttam Sharma

thank you, It was a nice post

Collapse
 
eneskaplan profile image
Enes Kaplan

For #2, instead of for-in, you can also use

Object.entries(myObject).forEach(([label, value]) =>{
    // do something..
    console.log(label, value)
})
Enter fullscreen mode Exit fullscreen mode

For #4, I think nesting ternaries reduces readability and when you come back to it, or someone else tries to understand it, it introduces a lot of mental overhead.

Collapse
 
pankajsanam profile image
Pankaj • Edited

Number#4 should be avoided. Using ternary for something like that makes your code complex/hard to read. Please don't teach wrong practices as most of the newbies read these articles and start writing the bad code.

Number#5 should also be corrected as highlighted in other comments.

Haven't checked after #5 as I'm convinced after reaching the 5th point that this article lacks the actual and practical knowledge by the author and not worth reading.

Collapse
 
julianengleheart profile image
Julian Engleheart

I’d suggest that any nested conditional statement can carry a heavy cognitive load. The author of this piece is demonstrating chained ternaries, where there is a single code path (no nested branching) that will return a value as soon as a condition is met or finally a default value if no conditions are met. A ternary expression is a different animal to if..else or switch statements, and it would be shame to see it thrown out in cases where it is the more suitable solution. There is an article by Eric Elliott on this subject.

Collapse
 
hakimio profile image
Tomas Rimkus

Never ever use nested ternary operators. It's a stinking unreadable mess.

Collapse
 
daxtersky profile image
Miko

Hi, cool art. Why in point 6 there's double check days[dayNumber]?

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

Yeah, that was unnecessary, thanks for pointing out! Got it fixed

Collapse
 
kikonen profile image
Kari Ikonen

Tip on ternary operation was bit on line "how to obfuscate code" line... Nested ternary operations make code harder to read, and resistant to change; if logic need to be changed, have to likely tear down first whole ternary operator mess to first of all understand logic, and secondly to be able to make logic change.

Collapse
 
cbiggins profile image
Christian Biggins

Thanks for this. Very helpful tips.
Note that I do think that code readability needs to be taken into consideration before using any available shortening option. Some of the examples above could add a perceived level of complexity and might have an unhelpful impressions on the dev.

Collapse
 
damian_cyrus profile image
Damian Cyrus

I would like to use #1 so many times, but it does not work with TypeScript, or is it just me 🤔

Collapse
 
eshimischi profile image
eshimischi
Collapse
 
damian_cyrus profile image
Damian Cyrus

Thanks @eshimischi, just like in the post described: it should work.

Too bad I don't get why it is not working in my last project with TS 4.8. Maybe it is a Windows environment thing ;)

Thread Thread
 
eshimischi profile image
eshimischi

Well it has nothing to do with a Windows environment, i’ll check it myself and let you know, mac is here

Thread Thread
 
damian_cyrus profile image
Damian Cyrus

I checked the code, and it looks like the issue was a type compatibility issue:

const getVowel = (letter: string): '' | 'a' | 'e' | 'i' | 'o' | 'u' => {
  // simple condition
  if (
    letter === 'a' ||
    letter === 'e' ||
    letter === 'i' ||
    letter === 'o' ||
    letter === 'u'
  ) {
    return letter; // ✅ (parameter) letter: "a" | "e" | "i" | "o" | "u"
  }
  // includes condition
  if (['a', 'e', 'i', 'o', 'u'].includes(letter)) {
    return letter; // ❌ (error) Type 'string' is not assignable to type '"" | "a" | "e" | "i" | "o" | "u"'.
  }
  return ''; 
};
Enter fullscreen mode Exit fullscreen mode

In this case TypeScript found in the simple condition the value and returns the right typed value.

In the includes condition the type of the variable is still string, and it could not find the correct value type.

From my view TypeScript is doing the right thing: it takes the original type (string) and does not modify the type in the second condition. In this case we use a form input onChange value, that is a string. Making it strict would mean we would need to convert the string type to the return type and that leaves us only with the multiple ||, as long as .includes() can't find the type like before.

Thread Thread
 
eshimischi profile image
eshimischi

That’s what i was about to say.. Typescript, i mean, has some extra work to do always

Collapse
 
wkylin profile image
wkylin.w

const name = user?.name ?? "Anonymous";

Collapse
 
alvisonhunter profile image
Alvison Hunter Arnuero | Front-End Web Developer • Edited
  1. Multiple string checks Alternative approach
const isVowel = letter => !!letter.match(/[aeiou]/g, '');
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️

The day number example wasn't the best choice. This would be easier with an array

Collapse
 
larisa00dila profile image
Larisa00dila

Hey

Collapse
 
the_riz profile image
Rich Winter

OHAI