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?

Soc
  • 7,425
  • 4
  • 13
  • 30
Ozzott
  • 63
  • 2
  • 8
  • Does this answer your question? [Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable) – Nick Parsons Dec 12 '19 at 01:04

3 Answers3

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
gavgrif
  • 15,194
  • 2
  • 25
  • 27
  • 1
    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`. – Soc Dec 12 '19 at 00:56
  • 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. – gavgrif Dec 12 '19 at 01:00
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.

Soc
  • 7,425
  • 4
  • 13
  • 30
0

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

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

AjayGohil
  • 101
  • 3