Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

The Error Object

JavaScript has a built-in error object that supplies information about an error when it occurs.

The error object contains two important properties: name and message.

Error Object Properties

Property

Description

name

Gets or sets the name of the error.

message

Gets or sets the error message (a string).

Error Name Values

The name property of an error can return six different values:

Error Name

Description

EvalError

An error has occurred in the eval() function

RangeError

A number “out of range” has occurred

ReferenceError

An illegal reference has occurred

SyntaxError

A syntax error has occurred

TypeError

A type error has occurred

URIError

An error in encodeURI() has occurred

Eval Error

An EvalError signifies an issue with the eval() function.

In newer versions of JavaScript, EvalError is no longer thrown. Instead, a SyntaxError is used.

Range Error

RangeError is thrown when a number falls outside the acceptable range of values.

For example, you cannot set the number of significant digits of a number to 500.

Example

let num = 1;
try {
  num.toPrecision(500);   // A number cannot have 500 significant digits
}
catch(err) {
  document.getElementById(“demo”).innerHTML = err.name;
}

Reference Error

ReferenceError is thrown if you attempt to reference a variable that has not been declared.

Example

let x = 5;
try {
  x = y + 1;   // y cannot be used (referenced)
}
catch(err) {
  document.getElementById(“demo”).innerHTML = err.name;
}

Syntax Error

SyntaxError is thrown if you attempt to execute code that contains a syntax error.

Example

try {
  eval(“alert(‘Hello)”);   // Missing ‘ will produce an error
}
catch(err) {
  document.getElementById(“demo”).innerHTML = err.name;
}

Type Error

TypeError is thrown when an operand or argument is not compatible with the expected type for an operator or function.

Example

let num = 1;
try {
  num.toUpperCase();   // You cannot convert a number to upper case
}
catch(err) {
  document.getElementById(“demo”).innerHTML = err.name;
}

URI (Uniform Resource Identifier) Error

URIError is thrown if illegal characters are used in a URI function.

Example

try {
  decodeURI(“%%%”);   // You cannot URI decode percent signs
}
catch(err) {
  document.getElementById(“demo”).innerHTML = err.name;
}

Non-Standard Error Object Properties

Mozilla and Microsoft define some non-standard error object properties:

fileName (Mozilla)

lineNumber (Mozilla)

columnNumber (Mozilla)

stack (Mozilla)

description (Microsoft)

number (Microsoft)

Avoid using these properties on public websites, as they may not be supported across all browsers.