The console.log(temp) statement is not just outside the loop, but also outside of the query’s .then() . That’s because after calling wixData.query, the code continues right to the console.log() statement. The results are only returned later in the .then() function when the query has finished.
If you move the console.log() inside the .then(), you will see your newly created array:
$w.onReady(function () {
let temp= [];
wixData.query("Products")
.find()
.then((result) => {
result.items.forEach((item) => {
//console.log(item["title]); This works fine, I can see the list of 15 product names
temp.push(item["title"]);
});
console.log(temp); // voila!
});
//console.log(temp); // here temp array is empty
});
See these articles for an explanation of Promises and asynchronous code: