JS is or is not if else

Advertisements

How could I simplify this action below.
I realize this is ridiculous.

But everything I’m trying to do, either one works and one doesn’t and vice versa.

I need to send data if this field is not empty. if it is empty, then don’t send it: admin|power

it’s either null or not

const mreq = await Model.findOne({
  where: {
    id: req.params.id,
    old: req.params.times
  }
})
if (!mreq) {
  return
} else if (mreq.admin == null) {
  return
} else if (mreq.admin) {
  res.json(mreq.admin)
} else if (mreq.power == null) {
  return
} else if (mreq.power) {
  res.json(mreq.power)
}

>Solution :

You don’t need all the branches that don’t return anything – just test for the two values to be .jsond in two ifs. Use optional chaining to keep things concise.

const mreq = await Model.findOne({ where: { id: req.params.id, old: req.params.times } })
if (mreq?.admin) {
    res.json(mreq.admin)
} else if (mreq?.power) {
    res.json(mreq.power)
}

Leave a ReplyCancel reply