Undefined Error V/s Reference Error
JavaScript Error Handling- at a glance
Undefined Error
An undeclared variable is assigned the value undefined at execution It is also of type Undefined. Any property that has not been assigned a value, assumes the undefined
value.
var undefinedVar;
console.log(undefinedVar); // undefined
console.log(typeof undefinedVar); // "undefined"
undefined(); // undefined
console.log(typeof undefined); // "undefined"
In JavaScript there is Undefined (type), undefined (value) and undefined (variable).
Undefined (type) is a built-in JavaScript type.
undefined (value) Any property that has not been assigned a value, assumes the undefined
value by default.
undefined (variable) is a global property whose initial value is undefined (value), Since its a global property we can also access it as a variable.
Something is undefined
when it hasn’t been defined. If you call a variable or function without actually creating it yet the parser will give you an not defined
error.
Simple fix to this,
var definedVar = 'Aastha';console.log(undefinedVar); // Aastha
console.log(typeof undefinedVar); // String
function definedFunction(){
return "Defined now"
}
console.log(undefined()); // Defined now
console.log(typeof undefined); // function
Reference Error
ReferenceError is thrown when trying to access a previously undeclared variable. A ReferenceError
is thrown when trying to dereference a variable that has not been declared.
function undefineddemo() {
console.log(variablenotdefined);
}
undefineddemo(); // here variablenotdefined is not referenced
Fix, Now this will give undefined TypeError
function undefineddemo() {
var variablenotdefined
console.log(variablenotdefined);
}
undefineddemo(); // Here variablenotdefined is not defined
Quick Fix,
function undefineddemo() {
var variabledefined = 100;
console.log(variabledefined);
}
undefineddemo(); // Here variablenotdefined is not defined
That’s all folks!