Kevin Kevin - 2 months ago 7
Javascript Question

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

In node 6.x the

querystring
module parses values into an object that does not extend from
Object.prototype
(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
localhost:8080/some/path?keyonly
and I want to check for the presence of
this.query.keyonly
? I expected that I could do
this.query.hasOwnProperty('keyonly')
which obviously doesn't work. What's the alternative?

Answer

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 http://example.org/foo?hasOwnProperty=hahacrashed).

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

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

You could also do something like:

var qs = querystring.parse('foo=bar');
if (Object.hasOwnProperty.call(qs, '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

Comments