2

I want to console.log my array like this without newlines:

const myarr = [ 1, 2, 3, 4, 5 ];

myarr.forEach((e) => console.log(e));

Actual result:

1
2
3
4
5

Desired result:

1 2 3 4 5

or

12345
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
AA Sog
  • 39
  • 1
  • 4
  • 1
    `console.log(...myarr)` – Teemu Mar 23 '20 at 16:13
  • Does this answer your question? [Chrome JavaScript developer console: Is it possible to call console.log() without a newline?](https://stackoverflow.com/questions/9627646/chrome-javascript-developer-console-is-it-possible-to-call-console-log-withou) Or more specifically [printing output same line using console log in javascript](https://stackoverflow.com/q/28620087/215552) – Heretic Monkey Mar 23 '20 at 16:15

5 Answers5

8

You could spread the array. Then all values are taken as parameters.

let array = [1, 2, 3, 4, 5];

console.log(...array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

To answer the actual question, there are two possible answers:

  1. If you are running in a browser, then by default, no, but according to this answer from Chrome JavaScript developer console: Is it possible to call console.log() without a newline? you can by making a virtual console on top of the browser's console.
  2. If you're using node, then you can use process.stdout.write(msg) from this answer Chrome JavaScript developer console: Is it possible to call console.log() without a newline?
iggy12345
  • 1,233
  • 12
  • 31
1

You can use .reduce() instead.

let myarr = [1,2,3,4,5];
const result = myarr.reduce((a, c) => `${a}${c}`, '');
console.log(result);

I hope this helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59
1

Why are you doing a separate console.log for every element in the array? You can just do:

console.log(myarr);

Or, if your array has objects in it and you want to see them all unrolled, you could do:

console.log(JSON.stringify(myarr));
frodo2975
  • 10,340
  • 3
  • 34
  • 41
1

You would have to stringify your output.

So either using something like JSON.stringify(myarr) or

let string = '';
for(let i = 1; i < 6; i += 1) {
  string += i + ' ';
}
console.log(string);

Edit: Btw, I'd suggest using camelCase when working with javascript. It's become a standard when defining variables and methods.

See: https://techterms.com/definition/camelcase

Gabson
  • 55
  • 12