Advertisement
728x90
Code snippet:
javascript
1const circle = {
2 radius: 20,
3 diameter() {
4 return this.radius * 2;
5 },
6 perimeter: () => 2 * Math.PI * this.radius,
7 };javascript
1console.log(circle.diameter());
2
3console.log(circle.perimeter());Output:
The output is 40 and NaN. Remember that diameter is a regular function, whereas the value of perimeter is an arrow function. The this keyword of a regular function(i.e, diameter) refers to the surrounding scope which is a class(i.e, Shape object). Whereas this keyword of perimeter function refers to the surrounding scope which is a window object. Since there is no radius property on window objects it returns an undefined value and the multiple of number value returns NaN value.
Advertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 13
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
356of476