• Coding Beauty
  • Posts
  • How functional try-catch transforms your JavaScript code

How functional try-catch transforms your JavaScript code

regex-reduce combo, try-catch upgrades, and more

In partnership with

Senior LatAm Tech Hiring in 24 Hours

CloudDevs is the largest pool of tech talent in LatAm. Our 10,000+ pre-vetted LatAm engineers have a minimum of 7 years of experience and are hand-selected for your project in just 24 hours.

Our talent is rigorously tested for problem-solving, tech stack and communication, and specialize in everything from AI and healthtech to fintech and web3.

Daily updates are here! Stay updated

reduce() is a head spinner.

Can you solve this? Regex seems tricky too.

GPTE AI: Discover over 5,000 new AI tools for productivity, design, content creation, and more. Check it out

At first you think you can just swap in anyone you like right?

Wrong. They're not what you think.

And we must learn the difference once and for all to avoid painful bugs down the line.

And what's this difference?

It's the incredible contrast in how they treat truthy and falsy values.

What are these?

Falsy: becomes false in a Boolean() or if :

  • 0

  • undefined

  • null

  • NaN

  • false

  • '' (empty string)

Truthy: every single thing else:

Now see what happens when you create a || chain like this:

How common is this?

It’s yet another instance where we want a value that depends on whether or not there’s an exception.

Normally, you’d most likely create a mutable variable outside the scope for error-free access within and after the try-catch.

But it doesn’t always have to be this way. Not with a functional try-catch.

A pure tryCatch() function avoids mutable variables and encourages maintainability and predictability in our codebase.

No external states are modified – tryCatch() encapsulates the entire error-handling logic and produces a single output.

Our catch turns into a one-liner with no need for braces:

So what does this tryCatch() function look like anyway?

From how we used it above you can already guess the definition:

Thanks for taking the time to read today’s issue.

Don’t let the bugs byte,
Tari Ibaba