Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
140
rated 0 times [  143] [ 3]  / answers: 1 / hits: 25812  / 6 Years ago, sun, december 30, 2018, 12:00:00

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?


More From » node.js

 Answers
12

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.


[#52851] Sunday, December 23, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
calicinthias

Total Points: 447
Total Questions: 101
Total Answers: 118

Location: Botswana
Member since Sat, Dec 31, 2022
1 Year ago
calicinthias questions
Sun, Jan 2, 22, 00:00, 2 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Mon, Aug 10, 20, 00:00, 4 Years ago
;