2

I have an es6 model that I want to do some basic validation on before it is posted to an endpoint. I wrote a simple isValid() method on the class which I want to return true or false, not truthy, falsey. Since && will return last check which was truthy, I shortcut the function by appending && true to the end of my validation check.

export default class foo {
  constructor (data = {}) {
    this._id = data.id
    this._name = data.name
  }
  isValid () {
    return this._id && this._name && true
  }
}

What I want to know is: Is this an appropriate way to return a true value in this context? Is there a better way to do this sort of validation in JS? I realize there are other ways to return a boolean doing 'if' statements, but I wanted this to be fairly concise and thought this might be a valid shortcut...

John Smith
  • 187
  • 7

2 Answers2

1

When you write it like

  isValid () {
    return this._id && this._name && true
  }

it will return true for a truthy value but will not return false for a falsy value.

In order to return true or false, you can use the Boolean constructor function like

isValid () {
    return Boolean(this._id && this._name)
  }

or else you can make use of ternary operator

isValid () {
    return this._id && this._name? true : false
  }

Demo snippet:

class foo {
  constructor (data = {}) {
    this._id = data.id
    this._name = data.name
  }
  isValid () {
    return Boolean(this._id && this._name)
  }
}

let foo1 = new foo({ id: 1, name: 'abc'});
let foo2 = new foo({ id: 2 });

console.log(foo1.isValid(), foo2.isValid());
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
1

You can shorthand !! to cast into boolean.

return !!(this._id && this._name)
Tu Tran
  • 458
  • 3
  • 9