Difference TypeError and ReferenceError

a 夏天 提交于 2019-12-03 13:49:21

A ReferenceError occurs when you try to use a variable that doesn't exist at all.

A TypeError occurs when the variable exists, but the operation you're trying to perform is not appropriate for the type of value it contains. In the case where the detailed message says "is not defined", this can occur if you have a variable whose value is the special undefined value, and you try to access a property of it.

See http://javascriptweblog.wordpress.com/2010/08/16/understanding-undefined-and-preventing-referenceerrors/ for some discussion related to this.

Here are the JavaScript error types:

The JavaScript 1.5 specification defines six primary error types, as follows:

EvalError: Raised when the eval() functions is used in an incorrect manner.

RangeError: Raised when a numeric variable exceeds its allowed range.

ReferenceError: Raised when an invalid reference is used.

SyntaxError: Raised when a syntax error occurs while parsing JavaScript code.

TypeError: Raised when the type of a variable is not as expected.

strong text URIError: Raised when the encodeURI() or decodeURI() functions are used in an incorrect manner.

Consider the following code:

function foo(){
 var d=1234;
 console.log(d.substring(1,2));     
}
foo();

This will have following output:

Exception: TypeError: d.substring is not a function This is because we have used the wrong type (number) for a given operation(substring which expects a string).The TypeError object represents an error when a value is not of the expected type.

function foo(){
 var d=1234;
 console.log(c);
}
foo();

This will have following output:

Exception: ReferenceError: c is not defined This is because the reference for the variable 'c' does not exist in either local or global scope and we are still trying to use it.A ReferenceError exception is thrown when a non-existent variable is accessed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!