JavaScript

JavaScript

Made by DeepSource

Returning values from setters JS-0037

Bug risk
Major
Autofix

Setters are special methods in JavaScript that override the assignment operator in object properties. The return value from a set method will never be usable.

In set methods, return statements should only be used for control flow. Returning actual values will only confuse the readers.

Bad Practice

const dataStore = {
  _data: null,
  set data(value) {
    if (this.isValid(value)) {
      this._data = value
      return true
    }

    // We're returning false to indicate that
    // the `set` was unsuccessful, but this
    // return value will *never* be usable.
    return false
  }
}

Recommended

const dataStore = {
  _data: null,
  set data(value) {
    if (this.isValid(value)) {
      this._data = value
    }
  }
}

console.log((dataStore.data = 1)) // 1