Why does console.log add a space at the end of my sentence when adding a value using the comma operator?

This question is hardly worth asking, but here I am.

Referring to the question above, here is the code and output

var port = 3000

console.log("Listening on port ", port)

Outputs "Listening on port 3000"

Notice the extra space added. Why is this happening?

+3


source to share


3 answers


By popular request, copied from comments:

Because that's what console.log does. You might also ask why he prints to the console instead of painting your bathroom blue. (Because the latter is not what it does.) :) If you don't need space, use the + operator to concatenate strings together.



The reason is probably because console.log

, at least in graphical clients, it has the ability to represent objects and arrays inline. This results in the displayed result not being a row, but rather a table with space separating each cell from the other. Each argument is thus presented separately.

Also, given what is console.log

used for debugging, console.log(i, j, a[i][j], a[i][j] / 2)

showing 3724.712.35

is actually not all that useful compared to 3 7 24.7 12.35

. And writing is console.annoying_log(i + ' ' + j + ' ' + a[i][j] + ' ' + a[i][j] / 2)

annoying. I had enough of this from Java when I was younger.

+6


source


From https://developer.mozilla.org/en-US/docs/Web/API/console.log method log

takes a list of Javascript objects as arguments

console.log (obj1 [, obj2, ..., objN);



You correctly pointed out in the documentation that objects are added together, but don't say the separator is a single space.

obj1 ... objN List of JavaScript objects to display. The string representation of each of these objects is added together to the order list and output.

+1


source


Should be

 console.log("Listening on port " + port)

      

How (I think) it can treat the arguments as an array and thus join it along with the default delimiter being a space

0


source







All Articles