Errors are a special 'type' in javascript. They happen when something goes wrong with your program, and they come with their own special control flow.

You can create an error in javascript with the following code:

Error('Oh no')
// => Error: Oh no

Throwing an error

When an error happens in Javascript we say: An Error was 'thrown'.

Most errors happen by accident, but we can throw an error too if we know our program has gone wrong:

throw Error('Oh no')

console.log('This never happens')

When an error is thrown the program immediately stops and no code below that point is run.

Accidental errors

We've already seen examples of errors which happen 'accidentally':

const array = null
array.length // <- throws a 'TypeError: array is null' Error!

console.log('This never happens')

Error Control Flow

Javascript has some extra control flow to help you manage errors called try and catch.

Javascript trys to run the code inside the try { } and if an error is thrown it immediately stops and jumps to the catch(error) { } and carries on from there.

Inside the catch error is the error that was thrown in the try block.

try {
  throw Error('Oh no')
  console.log('This never happens')
} catch (error) {

The same scope rules we learned before: Already declared and same or less indented, still apply.