0

I am adding a String and an array to an already created array myArray using push. However, when I print the updated myArray in the console after pushing, I only see the String added to myArray, not the added array, in myArray’s content. (The content is seen when I press the little arrow next to the myArray array in the console.) The added array isn’t being taken into account in the length of the updated myArray either. Why is this?

Note: The added array isn’t shown to be in the updated myArray, but when I pop the last element from the updated myArray, the array that was added (the one of interest) is returned. So it seems to be stored in myArray but not technically? What is going on?

My code:

var myArray = [1, 2, 3];

myArray.push('Jacob', ['Brandy', 2]);
console.log(myArray);

var removedValue = myArray.pop();

console.log(removedValue);

Current output:

Array(5) [ 1, 2, 3, "Jacob", (2) […] ]
    0: 1
    1: 2
    2: 3
    3: "Jacob"
    length: 4
    <prototype>: Array []

Expected output:

Array(5) [ 1, 2, 3, "Jacob", (2) […] ]
    0: 1
    1: 2
    2: 3
    3: "Jacob"
    4: ["Brandy", 2]
    length: 5
    <prototype>: Array []
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
hsivru
  • 55
  • 1
  • 8
  • Added a snippet for you and it's not showing the problem. Where are you logging this? Oh, i see it now in the Chrome console. Chrome logs live arrays so if you don't expand it before mutating it it will show the mutated array – pilchard Dec 01 '21 at 21:52
  • 1
    `console.log`, depending on platform, is a *live view* of an object that updates as it is mutated. If you want a *snapshot* of the state of an object at a particular point in time, use `console.log(JSON.stringify(obj))` – Jared Smith Dec 01 '21 at 21:53
  • @pilchard I'm using Firefox Web Developer tools – hsivru Dec 01 '21 at 21:53
  • ...and that would be why. – Jared Smith Dec 01 '21 at 21:53
  • see: [console.log() inconsistency with objects and arrays](https://stackoverflow.com/questions/24175017/google-chrome-console-log-inconsistency-with-objects-and-arrays) – pilchard Dec 01 '21 at 21:55
  • @JaredSmith I'm new to JavaScript. Can you explain why using Firefox's Web Dev tools is the problem. – hsivru Dec 01 '21 at 21:55
  • It's not a problem, but you have to be aware of how it logs data – pilchard Dec 01 '21 at 21:55
  • @hsivru For the reason I already said: logging an object to the console in dev tools doesn't print a snapshot of the value of an object at a point in time, it gives a *live view* of the object that updates as the state changes. When you use `.pop()` it alters the *previous* `console.log` – Jared Smith Dec 01 '21 at 21:56

0 Answers0