Skip to content

JavaScript Runtime errors

  • by

JavaScript runtime errors occur when the code is being executed and something unexpected happens that prevents the code from running properly. Here are some common runtime errors in JavaScript:

  1. TypeError: Occurs If performing an operation on a value that is not of the expected type. For example, trying to call a method on a null or undefined value.
  2. ReferenceError: When you try to reference a variable or function that has not been declared. For example, trying to use a variable that has not been defined.
  3. SyntaxError: This error occurs when there is a syntax error in your code. For example, a missing semicolon or a missing closing parenthesis.
  4. RangeError: If you try to use a value that is outside the range of valid values. For example, trying to create an array with a negative length.
  5. EvalError: This error occurs when there is an error in the eval() function. This function is used to evaluate a string as JavaScript code.

JavaScript Runtime errors example

Simple example code using a try-catch block to handle a runtime error in JavaScript:

<!DOCTYPE html>
<html>
<body>
    <script>
      try {
            // This code might throw a runtime error
            let value = null;
            let length = value.length;
            console.log(length);
        } catch (error) {
            console.error('Runtime error:', error.message);
            let length = 0;
            console.log(length);
        }
    </script>
</body>
</html>

Output:

JavaScript Runtime errors

Here’s another example:

try {
  // This code might throw a runtime error
  let value = JSON.parse('{"name":"John"}');
  console.log(value.age);
} catch (error) {
  // If a runtime error occurs, handle it here
  if (error instanceof TypeError) {
    console.error('Type error:', error.message);
    // Provide a fallback value or solution
    let value = { name: "John", age: null };
    console.log(value.age);
  } else {
    console.error('Runtime error:', error.message);
  }
}

Do comment if you have any doubts on this Js error topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading