String Concatenation

Heya,

I have a Question that is making me think too much, becuase there is for sure a really Simple Answer to it :sweat_smile:

So I wrote this

const vorname  = "Donald";
const nachname = "Duck"; 
console.log (vorname, + " " + nachname);

and The output is // OUTPUT: Donald 0Duck

Why is There a 0?

I’m pretty sure it’s the extra comma in vorname,

2 Likes

what is the Difference between the

, and + ?

There’s a very interesting explanation for this. Normally one would write this off and say, you don’t use commas in variable name concatenation and that’s the end of the story, but let’s see what documention says about commas!

The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand.

So let’s play with this idea:

x = (2, 3);
// output 3

x = (2, 2);
// output 2

x = ("word", + "fruit")
// output NaN (not  a number)

x = ("word", + " ");
//output 0

console.log(0 == " ")
//output: true

This is specifically why you got "Donald 0Duck"

The MDN documenation is again very helpful here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator


The short answer for your question is if you omit the comma it will work.

1 Like

Some more nuances

console.log (vorname, + " " + nachname);
// output: Donald 0Duck
x = (vorname, + " " + nachname)
console.log(x)
// output: 0Duck
console.log((vorname, + " " + nachname))
// output: 0Duck

I think this really goes down the rabbit-hole of javascript peculiarities…

2 Likes

console.log() will accept a comma-separated list of items to log…

console.log("apple","pear","orange");
// output: apple pear orange
2 Likes