twitch
Streaming on Twitch twice a week

Error handling with try-catch

JavaScript

With try and catch, we can react to errors in functions that could fail without our code crashing. If there is no error and the function succeeds, the catch-block is skipped.

// `try` to do something that could fail
try {
  // this may or may not be possible
  makeItBeFriday()

  // if we get here, the function worked
  console.log('It is Friday now!')
} catch (error) {
  // if something in `try` fails and throws an error, we end up here
  console.log('Sorry, it is not Friday now.')
}

More fire tips

Replacing all matches in a string

The String prototype’s replace function only replaces the first occurrence of a substring by default. We can extend that with a global flag on the expression.

JavaScriptregular expressions
Read fire tip

Read all fire tips →