DEV Community

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

Posted on • Updated on

7 Shorthand Optimization Tricks every JavaScript Developer Should Know 😎

Every language has its own quirks and JavaScript, the most used programming language, is no exception. This article will cover a plethora of JavaScript Shorthand Optimization tricks that can help you write better code, and also make sure this is NOT your reaction when you encounter them:

confused-face

1. Multiple string checks

Often you might need to check if a string is equal to one of the multiple values, and can become tiring extremely quickly. Luckily, JavaScript has a built-in method to help you with this.

// Long-hand
const isVowel = (letter) => {
  if (
    letter === "a" ||
    letter === "e" ||
    letter === "i" ||
    letter === "o" ||
    letter === "u"
  ) {
    return true;
  }
  return false;
};

// Short-hand
const isVowel = (letter) =>
  ["a", "e", "i", "o", "u"].includes(letter);
Enter fullscreen mode Exit fullscreen mode

2. For-of and For-in loops

For-of and For-in loops are a great way to iterate over an array or object without having to manually keep track of the index of the keys of the object.

For-of

const arr = [1, 2, 3, 4, 5];

// Long-hand
for (let i = 0; i < arr.length; i++) {
  const element = arr[i];
  // ...
}

// Short-hand
for (const element of arr) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

For-in

const obj = {
  a: 1,
  b: 2,
  c: 3,
};

// Long-hand
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
  const key = keys[i];
  const value = obj[key];
  // ...
}

// Short-hand
for (const key in obj) {
  const value = obj[key];
  // ...
}
Enter fullscreen mode Exit fullscreen mode

3. Falsey checks

If you want to check if a variable is null, undefined, 0, false, NaN, or an empty string, you can use the Logical Not (!) operator to check for all of them at once, without having to write multiple conditions. This makes it easy to check if a variable contains valid data.

// Long-hand
const isFalsey = (value) => {
  if (
    value === null ||
    value === undefined ||
    value === 0 ||
    value === false ||
    value === NaN ||
    value === ""
  ) {
    return true;
  }
  return false;
};

// Short-hand
const isFalsey = (value) => !value;
Enter fullscreen mode Exit fullscreen mode

4. Ternary operator

As a JavaScript developer, you must have encountered the ternary operator. It is a great way to write concise if-else statements. However, you can also use it to write concise code and even chain them to check for multiple conditions.

// Long-hand
let info;
if (value < minValue) {
  info = "Value is too small";
} else if (value > maxValue) {
  info = "Value is too large";
} else {
  info = "Value is in range";
}

// Short-hand
const info =
  value < minValue
    ? "Value is too small"
    : value > maxValue ? "Value is too large" : "Value is in range";
Enter fullscreen mode Exit fullscreen mode

5. Function calls

With the help of the ternary operator, you can also determine which function to call based on conditions.

IMPORTANT SIDE-NOTE: The call signature of the functions must be the same, else you risk running into an errors

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

// Long-hand
if (condition) {
  f1();
} else {
  f2();
}

// Short-hand
(condition ? f1 : f2)();
Enter fullscreen mode Exit fullscreen mode

6. Switch shorthand

Long switch cases can often be optimized by using an object with the keys as the switches and the values as the return values.

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

// Long-hand
let day;
switch (dayNumber) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
}

// Short-hand
const days = {
  0: "Sunday",
  1: "Monday",
  2: "Tuesday",
  3: "Wednesday",
  4: "Thursday",
  5: "Friday",
  6: "Saturday",
};
const day = days[dayNumber];
Enter fullscreen mode Exit fullscreen mode

7. Fallback values

The || operator can set a fallback value for a variable.

// Long-hand
let name;
if (user?.name) {
  name = user.name;
} else {
  name = "Anonymous";
}

// Short-hand
const name = user?.name || "Anonymous";
Enter fullscreen mode Exit fullscreen mode

That's all folks! 🎉

Finding personal finance too intimidating? Checkout my Instagram to become a Dollar Ninja

Thanks for reading

Need a Top Rated Front-End Development Freelancer to chop away your development woes? Contact me on Upwork

Want to see what I am working on? Check out my Personal Website and GitHub

Want to connect? Reach out to me on LinkedIn

I am a Digital Nomad and occasionally travel. Follow me on Instagram to check out what I am up to.

Follow my blogs for bi-weekly new tidbits on Dev

FAQ

These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.

  1. I am a beginner, how should I learn Front-End Web Dev?
    Look into the following articles:

    1. Front End Development Roadmap
    2. Front End Project Ideas
  2. Would you mentor me?

    Sorry, I am already under a lot of workload and would not have the time to mentor anyone.

Oldest comments (54)

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
 
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
 
jonrandy profile image
Jon Randy 🎖️

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

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
 
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
 
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
 
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
 
uttam_py profile image
Uttam Sharma

thank you, It was a nice post

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
 
larisa00dila profile image
Larisa00dila

Hey

Collapse
 
the_riz profile image
Rich Winter

OHAI

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
 
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
 
wilmela profile image
Wilmela

Cool

Collapse
 
vidipghosh profile image
Vidip Ghosh

Very useful.

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
 
hakimio profile image
Tomas Rimkus

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

Collapse
 
baltaguirre profile image
Baltasar Aguirre

Great post!! Thanks!!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.