Hax
Hax

Reputation: 154

Cannot read property even if the property exists

I don't understand why the following code says Cannot read property 'x' of undefined even if the property has been added after its object's definition.

let points = [
    { x:0, y:2 },
    { x:10, y:20 },
];

points[3] = { x:3, y:8, z:15 }
console.log(points[3])

// ok until here

points.dist = function() { 
    let p1 = this[0];
    let p2 = this[2];
    let a = p2.x-p1.x; let b = p2.y-p1.y; 
    return Math.sqrt(a*a + b*b);
};

points.dist();

Upvotes: 1

Views: 53

Answers (1)

Talha Akbar
Talha Akbar

Reputation: 10030

You initialized the array with 2 objects spanning indices 0 and 1. Then you added an object to index 3. However, in dist function, you are accessing index 2. Index 2 has no object defined.

let p2 = this[2]; // <-- It should be either 0, 1, or 3; 2 is never defined on array

You can inspect the array for its structure before using it:

let points = [
    { x:0, y:2 },
    { x:10, y:20 },
];

points[3] = { x:3, y:8, z:15 }
console.log(points);

Upvotes: 2

Related Questions