Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

print out variables

Hello,

I can't understand one thing. For instance, we have the current code. When we create a new var "message" it consists "<p>Hello, My name is " + person.name + "</p>"; but after creating a new variable it has already got different value, however, when we call the function "print" it prints out not last value but every line of var message? "Hello. My name is..." "I live in.." Thanks.

function print(message) {
  var div = document.getElementById('output');
  div.innerHTML = message;
}
var message = "<p>Hello, My name is " + person.name + "</p>";
message += "<p>I live in the " + person.country + "</p>";
print(message);

2 Answers

It's because you are concatenating the variable message by using the += operator.

the operator + contacts data together, in this case the variable message.

A small example to ilustrate what Jacob Mishkin said:

var value = 2;
value = 3; // the value is now 3
value += 4; // the value is now 3 (previous value) + 4 = 7;

basically, doing

value + = 4;

is the same as doing

value = value + 4; 

It's the same with Strings, if you use the += operator, you won't "replace" the message with the one you want - you will in fact "add it" / contactenate it with the one already in the element.