JavaScript Refresh – Errors and Bugs

Languages

Bugs are more difficult to find in JS because it’s grammar isn’t very strict.

true * "a sentence"

There are a couple times when JavaScript won’t know what to do and throw an error.

  • Bad syntax
  • Calling a non-function like a function
  • Trying to look up a property on undefined

Strict Mode

“use strict” at top of file.

  • JS will not auto declare undeclared bindings.
number = 1; // throws an error

Types

JS does not require you to declare a variable’s type.

Use Typescript to add type handling.

Tests

Tests are just functions that check to see if your code is doing what it’s supposed to.

Debugging

Debugging is the process of finding where a bug is happening.

Put a few well-placed console.log statements to learn more about what’s happening in the program.

You can also use your browser’s debugger. Set a break point, and you can inspect the variables at the break point.

Error propagation

Handle and anticipate errors in your programs. Gracefully fail.

Exceptions

If a problem happens in your function (like bad input), you can throw an exception.

Wherever you call the function, you can catch the exception and gracefully fail.

An exception is like another type of control flow.

Clean up after exceptions

Create code with fewer side effects.

Make you code idempotent. Even if it fails, you can run it, again, and it will clean up and pick up where it left off.

A try / catch block can also have a finally block.

Selective Catching

In JavaScript, you can only catch all exceptions or none. The exception you’re catching in your catch block might not be the exception you were expecting.

You can manually create a new class that extends the Error class and use instance of to check it.