What is the Output of this Code?

What is the Output of this Code?

Ferenc Almasi β€’ 2020 December 11 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

Given the following method calls in JavaScript, what is the output?

Copied to clipboard! Playground
const circle = {
    radius: 10,
    diameter() {
        return this.radius * 2;
    },

    perimeter: () => 2 * Math.PI * this.radius
};

circle.diameter();
circle.perimeter();
circle.js

The correct answer is NaNcircle.diameter executes without the problem but perimeter is defined as an arrow function. Arrow functions don’t bind their own context which means this.radius will be undefined. And 2 * Math.PI * undefined will be equal to NaN.

What happens if you call this in an arrow function?
If you would like to see more Webtips, follow @flowforfrank

What Is β€œthis”, After All? β€” A Look at JavaScript this Keyword

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.