Question:
can you explain this javascript in lamens terms?
worried guy
2012-01-06 03:16:15 UTC
I'm looking at a piece of code which includes this:

var message;
message = "Using the JavaScript library,
";
message = message + "The square root of " + number + "
";
message = message + "is " + sqRoot;

The output looks like this:

http://img13.imageshack.us/img13/9058/javascript.jpg

So my question is: How on earth is the message displaying like that?? How come it isn't displaying the ''Using the JavaScript library,'' bit 3 times?

I'm confused, hope someone can explain it for me.
Four answers:
Gardner
2012-01-06 03:23:24 UTC
message = message + says to take the existing message and add this to it.
Bogdan
2012-01-06 12:55:01 UTC
Your code goes something like this... First the message variable (because of the "var" in front of it) gets a null value, meaning its empty.



Then, you give the message variable a value that is - "Using the JavaScript library,
"; (notice you have the
which stands for new line). Ok, so far your message variable contains the string above.



After this, you make your message variable the old variable string (currently your message variable contains a string ... Using the JavaScript.... etc - this bit is accomplished by "message = message +") and add the new string which is - "The square root of " + number + "
";



And you do the same for the last message variable, thus resulting your image.



The new lines are given by the "
" HTML code.



Regards,

Bogdan's web resources and freebies - http://web.bogdanteodoru.com
MrFehr
2012-01-06 11:24:23 UTC
Coding works in lines, so it will see this:



var message; - this is what message means when it is referred to

message = "Using the JavaScript library,
"; - this is what message means

message = message + "The square root of " + number + "
"; - this is the previous message, plus more, and now it is the new message

message = message + "is " + sqRoot; - this is the previous message, plus more, once again it is now the new message



It will always refer to what it already knows (lines it's already read), if you added another line, that will become the new line.



Sorry, it is quite difficult to explain, hope this helps though.
Manas
2012-01-06 11:22:34 UTC
when you use message = message + "bla bla bla", it appends the new text after the original one.



here message is used in 3 different lines does not mean it will be showed 3 times. it means the content of the variable message has been modified 3 times by appending texts. finally the value of message is displayed.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...