Reputation:
When working with ajax requests, if a response property is either 1 (type: number) for true or 0 (type: number) for false, what is the best way to check if this is true. All of these examples work, just wondering if there is a preferred one to use and the reason it is preferred.
if (response.hasOwnProperty('test')) {
// 1
if (response.test === 1) {
alert('is true');
}
// 2
if (response.test) {
alert('is true');
}
// 3
if (response.test == true) {
alert('is true');
}
// 4
if (Boolean(response.test) === true) {
alert('is true');
}
// 5
if (response.test == 1) {
alert('is true');
}
}
Upvotes: 1
Views: 70
Reputation: 25322
As was said, it's mostly opinion based.
However, there are some pro and cons depends by the approach you're using.
First of all, the context is important: if it's code you're writing for yourself or it's a project with other developers that are collaborating; if you also wrote - and therefore you have control - on the backend, and so on.
In general, if it's something I've control AND it's not a production code, I would probably go for the second form: quick enough, clear enough - it's truthy or falsy - and I'm sure that the value returned from the backend are 0 and 1 for a reason.
In all the other scenario, I would go for the strict equal, so the first form: it's more explicit. Reading the second form, the only thing I know is that the value can be truthy or falsy, I've no idea what the actual value can be. If there is any change in the API - because, for instance, I do not have direct control on it, or maybe someone else change it in the project and forgot this piece of code - the code would fail. For example:
if (response.test === 1) {
// do something
} else if (response.test === 0) {
// do something else or do nothing
} else {
throw new Error("Unexpected value from response.test")
}
Even if you don't have the else
would be safe enough if the API would add a new value. For example, let's say that now the API can returns 0, 1, or 3. If you check for truthy values, 1 and 3 will be equals. But if you have:
if (response.test === 1) {
// do something
} else if (response.test === 0) {
// do something else or do nothing
}
You're good; your code will still works as intended, even if the API is extended.
Upvotes: 1