w3resource

JavaScript Class: Rectangle with area and perimeter methods

JavaScript OOP: Exercise-2 with Solution

Write a JavaScript program to create a class called 'Rectangle' with properties for width and height. Include two methods to calculate rectangle area and perimeter. Create an instance of the 'Rectangle' class and calculate its area and perimeter.

Sample Solution:

JavaScript Code:

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  calculateArea() {
    return this.width * this.height;
  }

  calculatePerimeter() {
    return 2 * (this.width + this.height);
  }
}

// Create an instance of the Rectangle class
const rectangle = new Rectangle(12, 10);

// Calculate area and perimeter of the rectangle
const area = rectangle.calculateArea();
const perimeter = rectangle.calculatePerimeter();

// Display the results
console.log(`Rectangle Area: ${area}`);
console.log(`Rectangle Perimeter: ${perimeter}`);

Sample Output:

"Rectangle Area: 120"
"Rectangle Perimeter: 44"

Note: Executed on JS Bin

Explanation:

The above exercise creates a "Rectangle" class with properties for width and height. It includes two methods, "calculateArea()" and "calculatePerimeter()", to calculate the area and perimeter respectively. An instance of the "Rectangle" class is created with width 12 and height 10, and then the area and perimeter are calculated using the respective methods. The results are then displayed on the console.

Flowchart:

Flowchart: Rectangle with area and perimeter methods.

Live Demo:

See the Pen javascript-oop-exercise-2 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

OOP Exercises Previous: Person with name, age, and country properties.
OOP Exercises Next: Vehicle and car subclass with details.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.