0

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:

// 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.

1
  • 7
    you aren't passing all 3 properties into Shape's constructor Commented Aug 18, 2022 at 13:40

2 Answers 2

3

Construction is just like another function and sequence of arguments should be same. when you pass super(sideLength); It sets name = 4 and other two arguments sets to undefined

You have to pass correct sequence of parameters in super function

super('Square', 4, sideLength);
Sign up to request clarification or add additional context in comments.

3 Comments

Ah okay, thank you so much. Would've been helpful if MDN included solutions to their exercises but oh well. Thank you so much!
Yes I will! I was trying to but it tells me I have to wait 5 minutes O.o
I think the MDN for super is pretty explicit in this case: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - super([arguments]) // calls the parent constructor. Just some helpful information for OP.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.