0

Can you please explain me why I can't access the testObj's key outside the .then() body?

Console.log results are shown in the comments.

//my object
let testObj = {
    title: "",
};

//my array
let testAr = [];

fetch("https://jsonplaceholder.typicode.com/todos/1")
    .then((response) => response.json())
    .then((data) => {
        testObj.title = data.title;
        testAr.push(data.title);

        console.log(testObj);
        //object log #1 - contents good
      // 
      //{title: "delectus aut autem"}
      // title: "delectus aut autem"
      // __proto__: Object 

      console.log(testAr);
      //array log #1 - contents good
      //
      //["delectus aut autem"]
      // 0: "delectus aut autem"
      // length: 1
      // __proto__: Array(0)
});

console.log(testObj); 
//object log #2 - cant access contents although they are displayed in log
//
// {title: ""}
// title: "delectus aut autem"
// __proto__: Object

console.log(testAr); 
//array log #2 - same as above
//
// []
// 0: "delectus aut autem"
// length: 1
// __proto__: Array(0)
VectorXY
  • 349
  • 1
  • 3
  • 12
  • @Quentin - We have [a better one](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) for this specific version of this question. :-) – T.J. Crowder Jan 05 '21 at 10:08
  • @ VectorXY - See also: [*console.log of element.children shows 0 length but has three entries when expanded later*](http://stackoverflow.com/questions/38660832/element-children-has-elements-but-returns-empty-htmlcollection) for the console aspect of the above. – T.J. Crowder Jan 05 '21 at 10:09

0 Answers0