0%

javascript-errors

TypeError: Cannot read properties of undefined (reading ‘xxx’)

This error occurs when you try to access a property of an object that is undefined.

1
2
let person = undefined;
console.log(person.age); // Uncaught TypeError: Cannot read properties of undefined (reading 'age')

ReferenceError: a is not defined

This is the most common error in JavaScript. It means that you are trying to use a variable that has not been declared.

1
console.log(a); // Uncaught ReferenceError: a is not defined

ReferenceError: Cannot access ‘a’ before initialization

This error occurs when you try to access a variable before it is declared. After ES6, this means you touch the (TDZ)temporal dead zone. temporal dead zone is the zone between the start of the block scope and the actual declaration of the variable.

1
2
console.log(a); // Uncaught ReferenceError: Cannot access 'a' before initialization
const a = 1;

TypeError: Assignment to constant variable.

This error occurs when you try to reassign a value to a constant variable.

1
2
const a = 1;
a = 2; // Uncaught TypeError: Assignment to constant variable.

RangeError: Maximum call stack size exceeded

See the following code, why it cause the RangeError: Maximum call stack size exceeded error?

1
2
3
4
5
6
7
8
9
10
11
class Person {
get name() {
return this.name;
}
set name(value) {
this.name = value;
}
}
const person = new Person();
person.name = 'Philip';
console.log(person.name); // undefined

The error is caused by the recursive call to the setter of name.

  1. person.name = 'Philip'; will call the setter set name(value).
  2. Inside the setter, this.name = value; will call the setter again. that’s an infinite loop.

How to fix it?
We can just use another name for the property, like _name.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Person {
get name() {
return this._name;
}

set name(value) {
this._name = value;
}
}

const person = new Person('zdd');
person.name = 'Philip';
console.log(person.name); // undefined

In this way,

  1. person.name = 'Philip'; will call the setter set name(value)
  2. Inside the setter function, we set the value to _name property, not the name property. So it will not cause the infinite loop.

You can find the details of getter and setter from here.