Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Instance returning undefined (JS)

I am currently learning JavaScript from MDN and have run into a weird issue that I can’t quite figure out. When I type newSquare.sideLength, it returns undefined, despite the instance having a number passed through it. What I need is for it to return the number 4 like I have passed through when creating the instance.

I’ve tried the same thing with a previous class and it worked perfectly fine but I don’t quite understand what is wrong here.

Here’s my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// OOJS 1
class Shape {
    name;
    sides;
    sideLength;
    constructor(name, sides, sideLength) {
        this.name = name;
        this.sides = sides;
        this.sideLength = sideLength;
    }

    calcPerimeter() {
        console.log(this.sides * this.sideLength);
    }
}

class Square extends Shape {
    constructor(sideLength) {
        super(sideLength);
        this.name = 'Square';
        this.sides = 4;
    }

    calcArea() {
        console.log(Math.pow(this.sideLength, 2));
    }
}

const newSquare = new Square(4);
console.log(newSquare.sideLength);

p.s. Sorry if this has a really simple solution, I’ve hit a block and I’m really trying to figure it out.

>Solution :

The Shape Class constructor, receive 3 properties, but in the square class, you only call the super constructor with 1 parameter, in this case, the name.
So when you call newSquare.sideLength this property has not been initialized and its value is undefined.
In Javascript, you need to respect the order of parameters in a constructor or function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading