Skip to main content

What is an error in JavaScript?

An error in JavaScript is an object that represents a problem that occurred while the program was running. When JavaScript hits a situation it cannot handle (for example, dividing by zero, referencing a nonexistent variable, invalid syntax, and so on), it creates an error object and "throws" it. If the error is not "caught", code execution stops.


The basic idea

Errors exist to control unforeseen situations - so the program does not "crash" unexpectedly, but can handle the problem and keep running correctly.


Example of an error occurring

javascript
console.log(a); // ReferenceError: a is not defined

Here the variable a is not declared, so the interpreter creates and throws a ReferenceError.


Handling errors (try...catch)

So the program does not stop, errors can be handled with a try...catch construct:

javascript
try { let result = JSON.parse("invalid JSON"); } catch (error) { console.log("An error occurred:", error.message); }

In this example the program does not crash, it simply prints a message:

javascript
An error occurred: Unexpected token i in JSON at position 0

Main error types

Error typeWhen it occurs
ReferenceErrorReferencing a nonexistent variable
TypeErrorWrong data type (for example, calling something that is not a function)
SyntaxErrorAn error in the code's syntax
RangeErrorA value out of its allowed range
EvalErrorIncorrect use of eval()
URIErrorAn error while working with URI-encoding functions (decodeURI, encodeURI)

Creating your own errors

You can create and throw an error yourself with throw:

javascript
function divide(a, b) { if (b === 0) { throw new Error("Cannot divide by zero!"); } return a / b; } try { divide(5, 0); } catch (err) { console.log(err.message); // Cannot divide by zero! }

Key methods and properties of the Error object

PropertyDescription
nameThe error type's name (TypeError, ReferenceError, etc.)
messageThe error description
stackThe stack trace (shows where the error occurred)

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.