How to achieve Python print
behavior in JavaScript with console.log
?
In Python, the following code:
print([1, 2], '\n', [3, 4])
produces this output:
[1, 2]
[3, 4]
However, in JavaScript:
console.log([1, 2], '\n', [3, 4]);
results in:
[1, 2] '\n' [3, 4]
What is the equivalent JavaScript statement to produce output similar to the Python print
?
You can use template literals to format the output similar to Python’s print behavior.
console.log(`${[1, 2]}\n${[3, 4]}`);
Output:
1,2
3,4
Combine the arrays into a string using join with \n as the delimiter.
console.log([1, 2].join(',') + '\n' + [3, 4].join(','));
Output:
1,2
3,4
Log each line separately, as console.log automatically adds a newline after each statement.
console.log([1, 2]);
console.log([3, 4]);
Output:
[1, 2]
[3, 4]