Reputation: 39
I have created REST API using node.js.since the API consumer is not correctly populating the object & some of the object attributes are coming "undefined"
and sometimes undefined
.
I have added a request interceptor that rejects API request if the required request parameters are missing
this is how my code looks like today. I just want to check if there is any better way to handle it.
(!variable_name || variable_name === 'undefined')
Upvotes: 0
Views: 85
Reputation: 222354
The most specific and self-explaining way is:
foo === undefined || foo === 'undefined'
While
!foo || foo === 'undefined'
condition is equivalent to
foo === undefined || foo === null || foo === false || foo === '' || foo === 0 || foo === NaN || foo === 'undefined'
This may result in false positive for any listed falsy value. If this is the case, !foo
shouldn't be used.
A shorter way is to coerce foo
to a string:
'' + foo === 'undefined'
This may result in false positive for any object that has toString()
returning undefined
. If this is undesirable, it shouldn't be used.
This is a workaround to fix a problem that shouldn't exist in the first place. undefined
shouldn't be indistinguishable from 'undefined'
string because this way there's no way to tell if it was originally 'undefined'
string ('undefined' is a word) or undefined
that was accidentally stringified.
Upvotes: 2