Suggest an editImprove this articleRefine the answer for “What is an error in JavaScript?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)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, it creates an error object and "throws" it. **Key point:** if the error is not "caught", code execution stops.Shown above the full answer for quick recall.Answer (EN)ImageAn **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 type | When it occurs | |---|---| | **ReferenceError** | Referencing a nonexistent variable | | **TypeError** | Wrong data type (for example, calling something that is not a function) | | **SyntaxError** | An error in the code's syntax | | **RangeError** | A value out of its allowed range | | **EvalError** | Incorrect use of `eval()` | | **URIError** | An 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 | Property | Description | |---|---| | `name` | The error type's name (`TypeError`, `ReferenceError`, etc.) | | `message` | The error description | | `stack` | The stack trace (shows where the error occurred) |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.