w3resource

JavaScript: Validate whether a given value type is error or not

JavaScript validation: Exercise-2 with Solution

Validate Error

Write a JavaScript function to validate whether a given value type is an error or not.

Sample Solution:-

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript function to validate whether a given value type is error or not</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function is_Error(input) {
   return input instanceof Error || toString.call(input) === '[object Error]';
}

console.log(is_Error(new Error('foo')));
console.log(is_Error(100));
console.log(is_Error('foo'));

Sample Output:

true
false
false

Flowchart:

Flowchart: JavaScript - Validate whether a given value type is error or not.

Live Demo:


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that determines if a given value is an instance of the Error class.
  • Write a JavaScript function that checks if a value’s constructor name is "Error" and returns a boolean.
  • Write a JavaScript function that verifies whether a value is a built-in error type (e.g., TypeError, ReferenceError) using instanceof.
  • Write a JavaScript function that accepts an array of values and extracts only those that are errors.

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to validate whether a given value type is Boolean or not.
Next: Write a JavaScript function to validate whether a given value type is NaN or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.