0

I know this is kinda dumb/useless, but I would love to understand it. I tried to call hasOwnProperty on a response-object but it always returns false. Why?

(await fetch('http://dummy.restapiexample.com/api/v1/employees')).hasOwnProperty('status');
Amir
  • 1,328
  • 2
  • 13
  • 27
faragos
  • 18
  • 3
  • The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a Response object). This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use the json() method (defined on the Body mixin, which is implemented by both the Request and Response objects.) – Jessica Bulldog Sep 10 '20 at 07:44
  • @JessicaBulldog why post this as a comment and not just add it to your answer? Code only answers discouraged – empiric Sep 10 '20 at 07:45
  • (await (await fetch('http://dummy.restapiexample.com/api/v1/employees')).json())..hasOwnProperty('status') which returns true. – Naren Sep 10 '20 at 07:47

2 Answers2

1

In Chrome, at least, the status property is not actually an own-property, but a getter on the prototype:

fetch('https://stacksnippets.net/js', { mode: 'no-cors' })
  .then((response) => {
    console.log(
      response.hasOwnProperty('status'),
      Object.getPrototypeOf(response).hasOwnProperty('status'),
      Object.getPrototypeOf(response) === Response.prototype
    );
    console.log(Object.getOwnPropertyDescriptor(Response.prototype, 'status'));
  });

So by referencing response.status, you'll be invoking the getter, despite the fact that the response does not have status as an own-property.

Error objects in some environment behave the same way - in earlier versions of Firefox, for example, the .message property is a property of Error.prototype, rather than being an own property of the error instance.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
-1
fetch('http://dummy.restapiexample.com/api/v1/employees')
  .then(response => response.json())
  .then(data => console.log(data.hasOwnProperty('status')));
  • 1
    Although this code might solve the problem, a good answer should explain **what** the code does and **how** it helps – BDL Sep 10 '20 at 08:33