I am very new at this, maybe I don’t know exactly how to ask this, but hope someone can help me.
I am using a short if statement inside a get function for a project but it is not returning what I expected. Here is my code:
async function getPrice(stock) {
const response = await fetch(`https://stock-price-checker-proxy.freecodecamp.rocks/v1/stock/${stock}/quote`, {
method: 'GET',
credentials: 'same-origin'
});
const { symbol, latestPrice } = await response.json();
return { symbol, latestPrice };
}
module.exports = function (app) {
app.route('/api/stock-prices')
.get(async function (req, res) {
// get all parameters necessary for response
const { stock, like } = req.query;
const { symbol, latestPrice } = await getPrice(stock);
// if cant find stock
if(!symbol) {
////// console.log(like);
res.json({ stockData: {
error: "invalid symbol",
likes: like ? 1 : 0
}});
////// console.log(like);
return;
}
});
};
Like comes from a checkbox input.
The short if-statement is always returning 1, whether "like" is true or false (checkbox is checked or not).
Both console.logs display "false", but the res.json still displays "likes: 1"
I have changed uncountable things and not yet found the reason for this, I don’t know if it might be somewhere else, but the rest of the code is a boilerplate, not made by me, so it is supposedly correct.
2
Answers
If
console.log
shows that you are returning"false"
(notice the quotations) then the value forlike
is coming back as a String type, not as a Boolean. If that is the case, both "true" and "false" will resolve as truthy because they are non-empty strings. If this is the case, we can simply alter the logic in the ternary slightly to explicitly check for a "true" string value.You may instead want to alter how that value is being saved at an earlier point so that it resolves as a Boolean, especially if you are going to use the value later as this can obviously cause trouble if you logically are expecting a Boolean but instead are given a string wrapped representation of one. But if this is a one-off value check, and if you know that the value can only either be "true" or "false" and nothing else, since it doesn’t seem like you are going to use the value again the above solution would probably be sufficient.
You could also add even more logic to it so that it accepts both Booleans and Strings and then coerce it into a number using the unary plus operator (
+
) to avoid the ternary. Something like:The + at the beginning of the conditional is the unary plus operator and when the conditions inside the parentheses resolve to either true or false it will coerce that boolean into either a 1 (for true) or a 0 (for false). This may be a little less clear to people though as to what is getting returned, and it may be more than you need if
like
can only ever be "true" or "false", but it should work well.An interesting way to convert a boolean string to a number: