I just started javascript a few days ago and was playing around with different ways to print the return value of a function.
<script>
function produceMessage(){
var msg= 'This should print';
return msg;
}
</script>
<span id="mySpan"></span>
Both these lines of code call methods like write or createTextNode to print the message.
document.body.appendChild(document.createTextNode(produceMessage()));
document.write(produceMessage());
However this line does not call a such a method but the return value is still printing.
document.getElementById('mySpan').innerHTML=produceMessage();
My intuition tells me that in order to have the return value appear on the screen, you need to call some sort of method that would allow it to be printed, like in this example:
document.getElementById('mySpan').innerHTML=document.write(produceMessage());
However this is incorrect and results in undefined output.
Setting the
innerHTMLof a element to a string results in the HTML of that element being changed to that string. So,produceMessage()mySpanto resultYour function
produceMessagereturns a string, so the innerHTML of that element is set toThis should print.Your next statement,
produceMessage()document.write()with the result, which appendsThis should printto the documentmySpanto the return value ofdocument.writedocument.writereturnsundefined, so the innerHTML of that element is set to the string representation ofundefined.