1

I mean, there's a really good chance I've just overlooked something simple here.

It's easier to explain in the code, but I'll try here too:

  • I create an object with a 'medals' property set to 5.
  • I console.log() the object and get the object with a medals property of 6.
  • Logging the actual object property using dot notation gets 5.
  • I then call a function to increment the medals property
  • Logging the object displays the same object as before, with a property of 6

In node and in the live snippets feature on this site, logging the object the first time gives the correct result of 5.

But it seems that in browsers that logging the object the first time actually retrieves the object after the following lines of code have run. Is this expected behaviour, or am I being thick?!

    var Person5 = function(name, YoB, height, weight) {
        this.name = name;
        this.YoB = YoB;
        this.height = height;
        this.weight = weight;
    };
    
    
    var Athlete5 = function(name, YoB, height, weight, olympicGames, medals) {
        Person5.call(this, name, YoB, height, weight);
        this.olympicGames = olympicGames;
        this.medals = medals;
    };
    
    Athlete5.prototype = Object.create(Person5.prototype);
    
    Athlete5.prototype.addMedal = function() {
        console.log('Number of medals before: ' + this.medals);
        console.log('Adding medal');
        this.medals++;
        console.log('Number of medals before: ' + this.medals);
    }
    
    var nick = new Athlete5('Nick', 1983, 6.0, 14, 5, 5);
    console.log(nick); // medals: 6 (in browser, it's 5 in the snippets)????
    console.log(nick.medals); // medals: 5
    nick.addMedal();
    console.log(nick); // medals: 6

Here's the result in Firefox, it says '5', but if you expand the object it then says '6' Firefox

and with chrome:Chrome

NickW
  • 1,207
  • 1
  • 12
  • 52
  • 3
    Admittedly I haven't read through the question in depth, but perhaps this will relate: When you `console.log()` an array or object, it doesn't log the array or object as it was *at the time of logging*, but rather shows the contents *at the time you expand it in the console*. It's "lazy". [Here's a simple example](https://jsfiddle.net/g78ns3m4/). – Tyler Roper Jun 20 '19 at 16:40
  • 2
    Possible duplicate of [Console.log showing only the updated version of the object printed](https://stackoverflow.com/questions/17320181/console-log-showing-only-the-updated-version-of-the-object-printed) and [Is Chrome's JavaScript console lazy about evaluating arrays?](https://stackoverflow.com/questions/4057440) – adiga Jun 20 '19 at 16:41
  • fair enough. I didn't know that was the case as I'm relatively new to JS and the browser, but yes that would definitely explain the behaviour, thanks – NickW Jun 20 '19 at 16:42
  • yup that looks right, i wasn't entirely sure if it was my error or not. thanks – NickW Jun 20 '19 at 16:43

0 Answers0