1

I have the following JavaScript code

let logs = [];
for (let j = 0; j < 10; j++) {
  logs[j] = { j };
  console.log('logs', logs);
}

I expect the output to be as follows

logs [ { j: 0 } ]
logs [ { j: 0 }, { j: 1 } ]
logs [ { j: 0 }, { j: 1 }, { j: 2 } ]
logs [ { j: 0 }, { j: 1 }, { j: 2 }, { j: 3 } ]
logs [ { j: 0 }, { j: 1 }, { j: 2 }, { j: 3 }, { j: 4 } ]
logs [ { j: 0 }, { j: 1 }, { j: 2 }, { j: 3 }, { j: 4 }, { j: 5 } ]...

And this is what I get when I run this code in the nodejs console.

But when I check in browser, I get the following output

logs [ { j: 0 },
  { j: 1 },
  { j: 2 },
  { j: 3 },
  { j: 4 },
  { j: 5 },
  { j: 6 },
  { j: 7 },
  { j: 8 },
  { j: 9 } ]

for every iteration

troglodyte07
  • 3,598
  • 10
  • 42
  • 66
  • you have to add 2 loops 1 for the vertical and another for horizontal. – vikscool Aug 13 '18 at 10:18
  • You tagged this as node, what version are you running? Is this really all that is logged out, or ist your console just scrolling away? – Luca Kiebel Aug 13 '18 at 10:18
  • @vikscool the loop works, put it in a node console or in your browser – Luca Kiebel Aug 13 '18 at 10:19
  • You need to write a nested loop for this. The first loop needs to take care of the row number and the second loop needs to take care of the column number. – R.D Aug 13 '18 at 10:21
  • @Luca I'm using node 8.9.4. No that is not all that is logged out.. I should've probably mentioned that – troglodyte07 Aug 13 '18 at 10:42
  • @vikscool loop is giving the output as expected in the node console but in browser, it's not. I mentioned that in the question – troglodyte07 Aug 13 '18 at 10:44

2 Answers2

3

You cannot control how browser displays the console.log outputs. One way to show the values like you mentioned is to stringify the objects to JSON (read what is JSON), and then show it on the console.

let logs = [];
for (let j = 0; j < 10; j++) {
  logs[j] = { j };
  console.log('logs', JSON.stringify(logs));
}
31piy
  • 23,323
  • 6
  • 47
  • 67
1

The code is actually doing what you expect it to. See the result in snippet below:

let logs = [];
for (let j = 0; j < 10; j++) {
  logs[j] = {
    j
  }
  console.log('logs', logs)
}

Notice that the result shown in stack-snippet is different from the one shown in the browser. That's because stack-snippet's console evaluates the variable logs immediately, whereas (most) browsers evaluate the value when you look at them. So by the time you look at them, the variable has 10 elements in the array.

A simple change to verify this would be to stringify the array before logging to console. The snippet below should produce the expected results:

let logs = [];
for (let j = 0; j < 10; j++) {
  logs[j] = {
    j
  }
  console.log('logs', JSON.stringify(logs));
}

Related: Is Chrome's JavaScript console lazy about evaluating arrays?

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55