1

I have a strange bug in my Angular code which I can't understand. I don't know whether it is related to the following behavior that I can't understand.

class Foo {
  bar: string;

  constructor(bar: string) {
    this.bar = bar;
  }
}

const fooList: Foo[] = [
  new Foo('A')
];

console.log(fooList[0]);
console.log(fooList);
fooList.forEach(foo => console.log(foo));

fooList[0].bar = 'B';

I'm using Angular 8 and when I run it on Firefox I see the following

Console output

What could it be?

andrea.ge
  • 1,937
  • 1
  • 18
  • 27
  • 1
    What's the strange behavior? – raven Apr 06 '20 at 11:29
  • 1
    `console.log(fooList)` in the snippet I posted prints "A", when I run the Angular application in my browser it prints "B" as you can see from the screenshot. – andrea.ge Apr 06 '20 at 11:31
  • see second console log: *bar: "B"*. @andrea.ge in chrome it shows *bar:"B"* for all console logs. Since they refer to the same object you are changing the value of *bar*. – omurbek Apr 06 '20 at 11:31
  • @andrea.ge console.logs are not synchronous. There is no guarantee they happen before or after the assignment. – Jared Smith Apr 06 '20 at 11:33
  • 1
    I am expecting "A" everywhere. If I see any "B", it's beyond my understanding. – andrea.ge Apr 06 '20 at 11:33
  • @OmurbekKadyrbekov the assignment happens *after* the objects are logged. OP is expecting synchronous printing and non-live views. – Jared Smith Apr 06 '20 at 11:36
  • In case you haven't noticed that your question is closed as a duplicate and as TL;DR: it's caused by a lazy object evaluation in the console. Nothing more, nothing less. It's a console specific curiosity. It has nothing to do with how the code actually behaves. – deceze Apr 06 '20 at 11:38
  • thank you very much, I read the other answers. So now I go back to the actual bug using `console.log` properly. – andrea.ge Apr 06 '20 at 11:39

0 Answers0