DEV Community

loading...

Discussion on: I Don't Use JavaScript Classes At All. Am I Missing Out on Something?

Collapse
theoboldalex profile image
Alex Theobold

One of my favourite use cases for a JS class is for building a custom service response wrapper that ensures consistency in the way my APIs return JSON. For example, I might want to send along a success prop and a message with my data whereby I can pass custom messages back to the client from my API.

A very simple example...

class ServiceResponse {
  constructor(data = "", success = true, message = "") {
    this.data = data;
    this.success = success;
    this.message = message;
  }
}

module.exports = ServiceResponse;
Enter fullscreen mode Exit fullscreen mode

This allows me to return a default success value of true and an empty message on each call along with the data unless something goes wrong, in which case, I can return early and set the success and message values appropriately.