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
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

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.