Kevin Kevin - 1 year ago 64
Javascript Question

How to check for Object key in javascript for object not inheriting from Object.prototype

In node 6.x the

module parses values into an object that does not extend from
(Although I have no idea why this change was made).

Given that, what is the expected way to check for query parameters that do not contain a value, i.e. someone called express or koa with
and I want to check for the presence of
? I expected that I could do
which obviously doesn't work. What's the alternative?

Answer Source

For the background behind the change, see the original PR here.

In general, you should not rely on foo.hasOwnProperty() since hasOwnProperty could be easily reassigned to something else (hence the reason for the querystring change -- imagine someone calling your web service with something like

As far alternatives, you could just check if the property is defined, for example:

var qs = querystring.parse('foo=bar');
if ( !== undefined) {
  // ...

You could also do something like:

var qs = querystring.parse('foo=bar');
if (, 'foo')) {
  // ...

but that isn't as efficient because hasOwnProperty() performs additional (and unnecesary in the case of querystring now) checks and uses .call() which is less efficient

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download