Start learning free

LESSON 248 OF 569 · FUNCTIONS & CLASSES

Rectangle Class in JavaScript

Practice O(1) Read the full explanation

A class bundles some values with the questions you can ask about them. Write a class Rectangle that remembers a rectangle's width and height, and can tell its area, its perimeter, and whether it is a square.

Implement the class Rectangle:

  • Rectangle(width, height) creates a rectangle with the given sizes.
  • area() returns the area of the rectangle: its width times its height.
  • perimeter() returns the perimeter: the length all the way around, twice the width plus twice the height.
  • isSquare() returns true if the width and the height are equal, and false otherwise.

Each line of the input is one rectangle: its width and its height. The test code first creates a Rectangle for every line, then asks each of them, in order, for its area, its perimeter and whether it is a square, and prints the three answers on one line, the boolean as True or False. So each object must keep its own sizes. The starter code spells these names the way your language does (in Go and Rust, Rectangle is a struct with methods).

 

Example 1:

Input:
    Rectangle(3, 4)
Output: 12 14 False
Explanation: The area is 3 · 4 = 12. Going around, the sides are 3 + 4 + 3 + 4 = 14.
The width and the height differ, so it isn't a square.

Example 2:

Input:
    Rectangle(5, 5)
Output: 25 20 True
Explanation: 5 · 5 = 25, and 4 sides of 5 make 20. Both sizes are 5: a square is a rectangle with equal sides.

Example 3:

Input:
    Rectangle(2, 10)
    Rectangle(10, 2)
Output:
20 24 False
20 24 False
Explanation: Two objects, each with its own sizes. Turning a rectangle on its side changes neither its area nor its perimeter.

 

Constraints:

  • 1 <= width, height <= 104
  • At most 10 rectangles per test.

Note:

Each method needs only the two sizes, so each one runs in O(1) time.

STEP 1 OF 4
    Ctrl + Enter to check

    JAVASCRIPT · FUNCTIONS & CLASSES

    Rectangle Class in JavaScript, explained

    Problem overview

    A class bundles values with the questions you can ask about them. Rectangle remembers a width and a height and answers three questions: its area(), its perimeter() and whether it isSquare().

    Each rectangle keeps its own sizes. A Rectangle(3, 4) has area 12, perimeter 14 and is not a square. A Rectangle(5, 5) has area 25, perimeter 20 and is a square. A Rectangle(2, 10) and a Rectangle(10, 2) both give 20 and 24: turning a rectangle on its side changes neither number.

    Approach

    The constructor stores the two parameters on the object, as this.width and this.height. Parameters disappear when the constructor ends, but properties on this stay with the object, so every other method can read them later. Each method then needs only those two numbers, so each one runs in O(1) time.

    Step by step

    1. Store the sizes. In constructor, assign width to this.width and height to this.height.
    2. Area. Return this.width * this.height.
    3. Perimeter. Going around, you walk along each side once, so the length is twice the sum of the two sizes. Put the sum in parentheses so that it is computed before the multiplication by 2.
    4. Square. Return this.width === this.height. A comparison is already a boolean, so no if is needed.

    The solution in JavaScript

    class Rectangle {
        constructor(width, height) {
            this.width = width;
            this.height = height;
        }
    
        area() {
            return this.width * this.height;
        }
    
        perimeter() {
            return 2 * (this.width + this.height);
        }
    
        isSquare() {
            return this.width === this.height;
        }
    }
    

    Using the class

    const a = new Rectangle(3, 4);
    console.log(a.area(), a.perimeter(), a.isSquare());
    const b = new Rectangle(5, 5);
    console.log(b.area(), b.perimeter(), b.isSquare());
    const c = new Rectangle(2, 10);
    const d = new Rectangle(10, 2);
    console.log(c.area(), c.perimeter(), c.isSquare());
    console.log(d.area(), d.perimeter(), d.isSquare());
    console.log(a.width, b.width);
    

    This prints:

    12 14 false
    25 20 true
    20 24 false
    20 24 false
    3 5
    

    The last line shows that each object has its own width: a holds 3 and b holds 5. The lesson's tests print booleans as True and False; JavaScript itself writes true and false.

    Common mistakes

    • Forgetting this in the constructor. Writing width = width; only assigns the parameter to itself, and nothing is stored on the object. A method that reads this.width then gets undefined.
    • Forgetting this in a method. Writing return width * height; inside area() looks for a variable called width, and fails with ReferenceError: width is not defined. Inside a method, the sizes are always reached through this.
    • Perimeter without parentheses. 2 * this.width + this.height doubles only the width. For Rectangle(3, 4) it gives 10 instead of 14.
    • Using = instead of === in isSquare: a single = assigns, so the method would overwrite the height.

    Testing

    A few inputs worth trying, with what the class returns for them:

    Rectanglearea()perimeter()isSquare()
    (1, 1)14true
    (1, 10000)1000020002false
    (10000, 10000)10000000040000true

    The largest sizes in the constraints give an area of 100000000. JavaScript numbers are doubles, which are exact for whole numbers up to 2 to the power 53, so there is no overflow to worry about.

    The properties are ordinary and public, so code outside the class can read and change them. After const r = new Rectangle(3, 4); r.width = 6;, r.area() returns 24 and r.perimeter() returns 20: the methods always use the current values. Keeping the sizes inside the object is what makes the methods short: they take no parameters at all.

    What new does

    Writing new Rectangle(3, 4) creates an empty object, runs the constructor with this pointing at that object, and hands the object back. After const a = new Rectangle(3, 4), calling a.area() runs the method with this pointing at a, so this.width is 3. Calling b.area() runs the same code with this pointing at b. The class is written once; every object gets its own copy of the data.

    Keep going with JavaScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free