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

6
  • you have to add 2 loops 1 for the vertical and another for horizontal. Commented Aug 13, 2018 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? Commented Aug 13, 2018 at 10:18
  • @vikscool the loop works, put it in a node console or in your browser Commented Aug 13, 2018 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. Commented Aug 13, 2018 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 Commented Aug 13, 2018 at 10:42

2 Answers 2

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));
}

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.