How to print all the Elements of an Array in single line in JavaScript??


How we can print all the elemnts of an array in single line using console.log(),
without converting it to string or creating a new string of the array elements??

1 Answer

3 years ago by

You can directly use the array in console.log like following

let arr = ['a', 'b', 'c'];
console.log(arr);  // => [ 'a', 'b', 'c' ]

or you can join them

let arr = ['a', 'b', 'c'];
console.log(arr.join(", ")); //=> a, b, c

you can also use JSON.stringify

let arr = ['a', 'b', 'c'];
console.log(JSON.stringify(arr)); //=> ["a","b","c"]

using reduce is another way

let arr = ['a', 'b', 'c'];
console.log(arr.reduce((res, ele) => res+ ' ' + ele, '')); //=> a b c

3 years ago by cody