Predict the output of the following javascript code
const shape = {
radius: 10,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius,
};
console.log(shape.diameter());
console.log(shape.perimeter());
Quiz Explanation
In this code, an object named shape
is defined, which contains properties for radius
, diameter
, and perimeter
. Let's analyze the code and its output:
radius: 10,
: This sets the propertyradius
of theshape
object to10
.diameter() { return this.radius * 2; },
: This defines a methoddiameter
on theshape
object, which returns the diameter of the shape. Inside the method,this.radius
refers to theradius
property of theshape
object.perimeter: () => 2 * Math.PI * this.radius,
: This defines a methodperimeter
using an arrow function. Arrow functions do not have their ownthis
context, sothis
inside an arrow function refers to the enclosing scope'sthis
. However, in this case, since the arrow function is defined in the global scope,this
refers to the global object (window
in a browser orglobal
in Node.js). As a result,this.radius
inside the arrow function will not refer to theradius
property of theshape
object but will beundefined
orNaN
.console.log(shape.diameter());
: This logs the result of calling thediameter
method of theshape
object. It correctly calculates the diameter as2 * radius
, which is20
.console.log(shape.perimeter());
: This logs the result of calling theperimeter
method of theshape
object. However, sincethis.radius
inside the arrow function ofperimeter
is not referring to theradius
property of theshape
object, but ratherundefined
orNaN
, the result will beNaN
.
So, the output of the code will be:
20
NaN
The diameter is correctly calculated using the diameter
method, but the perimeter calculation using the arrow function results in NaN
due to incorrect usage of this
.