1

JavaScript question #Day 3

 2 years ago
source link: https://dev.to/soorajs98/javascript-question-day-3-3ahk
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Cover image for JavaScript question #Day 3

JavaScript question #Day 3

Jul 14

・1 min read

What's the output ?

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

console.log(shape.diameter());
console.log(shape.perimeter());
Enter fullscreen modeExit fullscreen mode
  • A: 20 and 62.83185307179586
  • B: 20 and NaN
  • C: 20 and 63
  • D: NaN and 63

Answer: B

Note that the value of diameter is a regular function, whereas the value of perimeter is an arrow function.

With arrow functions, the this keyword refers to its current surrounding scope, unlike regular functions! This means that when we call perimeter, it doesn't refer to the shape object, but to its surrounding scope (window for example).

There is no value radius on that object, which returns NaN.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK