'How to save ternary operator as a value on JavaScript (Node.js)?
I try code to create method in Node.js (Express). I want to using ternary operator for return data and this following code is work perfectly.
const update = async (req, res) => {
try {
const { id } = req.params
const { name, price } = req.body
if (!(name && price)) {
!name ?
res.status(409).json({
status: res.statusCode,
message: "Name must not empty!"
}) :
res.status(409).json({
status: res.statusCode,
message: "Price must not empty!"
})
} else {
await Product.update({ name: name, price: price}, {
where: {
...
}
})
}
} catch (err) {
console.log(err)
}
}
But, can I assigned / save ternary operator as a variable for simple code?
I try to following code to save as a variable but still not working.
const x = !name ? "Name" : "Price"
Thank you.
Solution 1:[1]
So, after few minutes later and research from internet. I get solution from ThoughtCo.
const update = async (req, res) => {
try {
const { id } = req.params
const { name, price } = req.body
if (!(name && price)) {
const x = (!name) ? "Name" : "Price"
res.status(409).json({
status: res.statusCode,
message: `${x} must not empty!`
})
} else {
await Product.update({ name: name, price: price}, {
where: {
...
}
})
}
} catch (err) {
console.log(err)
}
}
First, I assign Name/Price to variable using ternary-operator and using template literals.
In my opinion, this following code is more simple than before.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rahmat Oktrifianto |
