Keith Grout
Keith Grout

Reputation: 909

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

This question is almost not worth asking, but here I am.

Referencing 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 thrown in there. Why does this occur?

Upvotes: 8

Views: 10539

Answers (3)

Amadan
Amadan

Reputation: 198446

By popular demand, copied from comments:

Because that's what console.log does. Might as well ask why it prints on the console instead of painting your bathroom blue. (Because the latter is not what it does). :) If you don't want the space, use + operator to stitch strings together.

The reason is, likely, the fact that console.log, at least in graphical clients, has the ability to present objects and arrays inline. This makes the displayed result not really a string, but more of a table, with the space separating each cell from another. Each argument is, thus, presented separately.

Also, considering that console.log is used for debugging, console.log(i, j, a[i][j], a[i][j] / 2) showing 3724.712.35 is not really all that useful, when compared to 3 7 24.7 12.35. And writing console.annoying_log(i + ' ' + j + ' ' + a[i][j] + ' ' + a[i][j] / 2) is annoying. I had enough of that from Java, when I was younger.

Upvotes: 8

user2314737
user2314737

Reputation: 29397

From https://developer.mozilla.org/en-US/docs/Web/API/console.log the method log takes as arguments a list of Javascript objects

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

You're right in the documentation it says that the objects are appended together but it doesn't say that the separator is a single space.

obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output.

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 60017

Should be be doing

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

As (I think) it might be treating the arguments as an array and thus join it together with a default delimiter being a space

Upvotes: 1

Related Questions