JS - What is output Question 3

0

Understanding Arrow Functions in JavaScript Objects




Let's explore how arrow functions behave within JavaScript objects using the following example:

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

console.log(shape.diameter());
console.log(shape.perimeter());

In this code snippet, we have an object named shape with properties radius, diameter, and perimeter. The diameter method is a regular function, while the perimeter method is an arrow function.

What do you think the output of this code would be?

The output would be:

20
NaN


Let's understand why:

1. shape.diameter(): This method returns this.radius * 2. Since diameter is a regular function, this refers to the object shape, and this.radius correctly accesses the radius property of shape, resulting in 20.

2. shape.perimeter(): This method calculates the perimeter of the shape using the formula 2 * Math.PI * this.radius. However, since arrow functions do not have their own this, they inherit the this value from the enclosing scope. In this case, the arrow function is defined within the context of the global scope (outside of any function or object), so this refers to the global object (e.g., window in a browser environment). Since there is no radius property in the global scope, this.radius evaluates to undefined, resulting in NaN (Not a Number).

This demonstrates how arrow functions behave differently compared to regular functions, especially in the context of object methods and their usage of this.

Tags:

Post a Comment

0Comments

Post a Comment (0)