0

why does "cars[0].name = 37" executes earlier than it have to?

var cars = [{name: "First"}, {name: "Second"}, {name: "Third"}];
var guns = [];

for (var i = 0; i < cars.length; i++) {
  guns.push(cars[i]);
}

console.log(guns);  // [{name: 37}, {name: "Second"}, {name: "Third"}]

cars[0].name = 37;

I've heard about hoisting, does it have something to do with it?

https://jsfiddle.net/r3wu867c/

undernet
  • 57
  • 1
  • 8
  • 1
    Console is showing most updated value – brk May 12 '20 at 15:32
  • @brk and how to fix it? – undernet May 12 '20 at 15:36
  • 1
    We can't reproduce your output with the given code. – Igor May 12 '20 at 15:37
  • 4
    You don't have to fix it, it is working properly - the console you're using is just updating the object for you after you change it. – Ashley May 12 '20 at 15:37
  • @Igor I'm running it in jsfiddle – undernet May 12 '20 at 15:38
  • `I'm running it in jsfiddle` ← Please include that link in your question. – Igor May 12 '20 at 15:39
  • @Igor ok, done. – undernet May 12 '20 at 15:41
  • 1
    This answer has an explanation for it: https://stackoverflow.com/a/24176638/746914 – popen2 May 12 '20 at 15:41
  • Your output still looks the same / correct even in [jsfiddle](https://jsfiddle.net/r3wu867c/). It shows 2 calls to `console.log`. The first one shows the same output as the code above, the second (after the `cars[0].name = 37`) shows the updated value. – Igor May 12 '20 at 15:41
  • @Igor I'm using a browser console, not the site's one – undernet May 12 '20 at 15:44
  • 1
    Execution order can be unpredictable in Javascript because code executes asynchronously. For example line 3 might execute before line 2 is finished executing - which could create problems if Line 3 expects Line 2 to have finished executing. You can avoid this problem and control the execution order by using Async functions / Await / Promises. – gnorman May 12 '20 at 15:46
  • 2
    @gnorman This code is not asynchronous, it is synchronous. – Ashley May 12 '20 at 15:51

0 Answers0