hasOwnProperty is not a function in Node.js?

Viewed 20766

I am going to test if 'session' property exists:

console.log(queryData)
console.log(typeof queryData)
if ('session' in queryData) {
  console.log('in')
}
else {
  console.log('not in')
}
if (queryData.hasOwnProperty('session')) {
  console.log('has own propety')
}

Its result is:

[Object: null prototype] { session: '0geBdiCsfczLQiT47dd45kWVN2Yp' }
object
in
/home/ubuntu/22.enmsg/cli/main.js:72
  if (queryData.hasOwnProperty('session')) {
                ^

TypeError: queryData.hasOwnProperty is not a function

Why does the hasOwnProperty NOT work?

3 Answers

Most objects in javascript inherit from Object; it's possible to intentionally create objects that inherit from nothing (i.e., null), and therefore they won't have any of the typical methods you'd expect to live on the object.

You would normally know if your code was doing this, so the object might be something passed to you from another library.

A way around the error is to call hasOwnProperty on Object explicitly, and bind it to the object, like so:

// Calls "hasOwnProperty" on queryData, even if queryData has
// no prototype:
console.log(Object.hasOwnProperty.bind(queryData)('session'));

EDIT: Just editing to add an opinion, which is that a much better line for your purposes is the simple truthy check if (queryData.session) {. The vagueness of this check is a strength when what you're asking is "did a session get passed?" - if session is null, undefined, false, empty string, or the key is missing altogether, the answer is clearly "no".

The easiest solution is to convert your null-prototype object to a standard javascript Object. You can do so by:

OBJjavascript = JSON.parse(JSON.stringify(objNullPrototype));
Related