1

const shape = {
  radius: 10,
  diameter() {
    return this.radius * 2;
  },
  perimeter: () => 2 * Math.PI * this.radius
};

console.log(shape.diameter());
console.log(shape.perimeter());

I know the diameter is 20, but why perimeter shows NaN?

1

3 Answers 3

4

This is a scope issue - the radius variable is not available inside the perimeter method and so is undefined. Changing the function to a regular method resolves the issue.

const shape = {
  radius: 10,
  diameter() {
    return this.radius * 2;
  },
  perimeter() {
    return 2 * Math.PI * this.radius
  }
};

console.log(shape.diameter()); //gives 20
console.log(shape.perimeter()); // gives 62.83185307179586

Sign up to request clarification or add additional context in comments.

2 Comments

When used in an arrow function (() => ...), the scope of this is the same scope as where the function is defined. In this case, it is window.
Thanks @Soc - that means that in order to have access to the radius variable - it would need to be in the global scope and outside of the shape object.
0

Depending on how you plan to use it, you may be better served with a class. In the example below, this in the arrow function refers to the Circle instance.

class Circle {
  constructor(radius) {
    this.radius = radius;
  }
  
  diameter() {
    return this.radius * 2;
  }
  
  perimeter = () => 2 * Math.PI * this.radius;
}

const shape = new Circle(10);

console.log(shape.diameter());
console.log(shape.perimeter());

That said, if you are using a class, I prefer the way that diameter is defined over perimeter as an arrow function.

Comments

0

hello perimeter as function not used arrow function(() =>)

perimeter() { return 2 * Math.PI * this.radius }

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.