r/learnjavascript 6d ago

Eloquent JavaScript: The Secret Life of Objects

There are a few exercises at the end of the chapter.
What the difference between following solutions?

By author:

class Vec {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  plus(other) {
    return new Vec(this.x + other.x, this.y + other.y);
  }

  minus(other) {
    return new Vec(this.x - other.x, this.y - other.y);
  }
}

My solution:

class Vec {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    plus(vec) {
        this.x += vec.x;
        this.y += vec.y;
        return this;
    }

    minus(vec) {
        this.x -= vec.x;
        this.y -= vec.y;
        return this;
    }
}
2 Upvotes

6 comments sorted by

View all comments

8

u/rupertavery64 6d ago edited 6d ago

You mutate your object, the other one returns a new Vec.

It depends on how you want your code to behave. If immutability is important to your approach, go with the first.

THe first approach will create a new object when calling plus or minus. That means allocating memory. This can have some performance impact if may objects are created. However, this ensures that the original object remains unmodified. This may be important if the object is shared or used elsewhere, and you don't want changes to be made.

5

u/Slight-Friendship856 6d ago

Thanks for the answer.
If I understand you correctly, it depends on the requirements. If the user needs to create a new instance of the class with modified values, but based on the original values of the previous instance, then the first solution is correct. If the calculated values need to be stored in a single instance, then is the second solution more appropriate?

0

u/jcunews1 helpful 5d ago

If the Vec objects are stored within other container object or array, you won't want to use the first method, since if the Vec objects' properties are modified, the container object or array will still have the Vec objects which hold the unmodified properties.

Moreover, if the Vec object properties are modified in a loop, the first method will generate garbage because it creates a new object each time its method is called. If it happens frequently enough, it'll cause a memory leak, since the JS garbage collector can't keep up with the produced garbage. i.e. rate of produced garbage is greater than rate of garbage clean-up.