Need help understanding how the + operator works with concatenation

Do you know why? I’ve been stuck on this step for an hour and I can’t find the answer to it anywhere :exploding_head:

can you share your code?

function pick(guess) {
  const numbers = [];
  while (numbers.length < 10) {
    numbers.push(Math.floor(Math.random() * 11));
  }
  text.innerText = "You picked " + guess + ". Here are the random numbers:\n";
  for (let i = 0; i < 10; i++) {
    text.innerText += numbers[i] + "\n";
  }
}

I finished the course, but I was wondering why " it needs to be concatenated using a plus sign" as I’ve not seen this in the previous courses. Thanks.

I’m currently working on this module, and though I figured it out, I’m still a bit confused as to why the concatenated operator was required? Is it always required when adding a new line with anything other than a string? Thoughts @freeCodeCamp ?

Hi @n_vietlong and @EmanF !

Welcome to the forum!

I moved this conversation into its own topic.

It looks like both of you essentially have the same question about how the + operator works.

The answer is that the + operator has two purposes.
One purpose is to add numbers
The other purpose is to concatenate strings

Here is a codepen showing different examples of the plus operator

Also, MDN docs has a good explanation what what is happening

But here is the summary of it.

When working with 2 number types, then the + is used to add those numbers

3+7 // 10

If you have two strings, then the + operator is for string concatenation

"Hello " + "World" // "Hello World"

if you have a string and a number, then the number would be converted to a string type and then the + would use string concatentation

9 + " random text" //9 random text

the newline character is used to create a new line

function stringsWithNewlines(str1, str2) {
  return str1 + "\n" + str2;
}

console.log(stringsWithNewlines("Roses are red", "Violets are blue,"));

// result
"Roses are red
Violets are blue,"

hope that helps

1 Like

It is one way (there are more) to craft a longer string where the content of a variable (the value) is introduced as part of the larger string.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.