0

please what does the second line of the following code mean, is it a tenary operation, if it's not then what is it and what does it mean

   const user = await User.findOne({ email: req.body.email });
   !user && res.status(404).json("user not found");
davies
  • 21
  • 4
  • The ternary operator is `?` followed by `:`. `&&` is the [AND logical operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#logical_operators). This is just a "witty" one-liner that makes use of [short-circuit evaluation](https://stackoverflow.com/questions/12554578/does-javascript-have-short-circuit-evaluation). – Álvaro González Nov 03 '21 at 08:43
  • 1
    It's an (in my opinion) ugly way to write the equivalent of `if (!user) res.status.....` – CherryDT Nov 03 '21 at 09:19

1 Answers1

4

It is not a ternary operator. The && operator is evaluating the left part, after coercing it to boolean if it is not. Then, if it turns true, it evaluates the right part after && and return the resulting value. But if it turns false, it returns the left part (not coerced).

The ! operator do two things : it coerces into boolean and returns the opposite value.

So here, if there is a user found in the first line, !user will be false and res.status(404).json("user not found") will not be evaluated.

If on the contrary no user was found, !user will be true and the second line will return a status 404.