Search code examples
javascriptgoogle-chromefirefoxconsole.logorder-of-execution

Question regarding Console.log in Chrome and Firefox


i'm meditating about this:

console.log in chrome and firefox shows the same result, before and after sorting (the result after sorting). a quick test in the playcode.io editor shows the results as expected. The alert method in chrome works also properly. Does anybody know about the background of this?

Found this Thread: JavaScript console.log execution order?

But i don't really get it...

let data = [

    {A: 100232}, 
    {A: 223434},
    {A: 233434},
    {A: 645455},
    {A: 212334},
    {A: 34343},
    {A: 743434},

];

console.log(data);
data.sort(function(a, b){return b.A - a.A}); 
console.log(data);

Solution

  • It is not a problem, it is how the console.log works in some browsers. It is printing a link to the object, and once you open this object in the console it shows a current version of the object. See docs:

    Don't use console.log(obj), use console.log(JSON.parse(JSON.stringify(obj))).

    This way you are sure you are seeing the value of obj at the moment you log it. Otherwise, many browsers provide a live view that constantly updates as values change. This may not be what you want.

    To see the version of the object in the moment of console logging try this:

    let data = [
    
        {A: 100232}, 
        {A: 223434},
        {A: 233434},
        {A: 645455},
        {A: 212334},
        {A: 34343},
        {A: 743434},
    
    ];
    
    console.log(JSON.stringify(data));
    data.sort(function(a, b){return b.A - a.A}); 
    console.log(JSON.stringify(data));