The same output I get in a console.log is not posting to the HTML div and I cannot figure out why.
I am expecting this array to print:
["Thief", "The Lion", "Harry Potter", "Lord of the Rings"]
const myLibrary = ["Thief", "The Lion", "Harry Potter", "Lord of the Rings"];
function Book() {
// the constructor
}
var bookLength = myLibrary.length;
function addBookToLibrary() {
for (var b = 0; b < bookLength; b++)
console.log(myLibrary[b]);
return myLibrary[b];
}
var labels = document.getElementById("myBooks").innerHTML;
labels = addBookToLibrary();
<p>My list should be below</p>
<p id="myBooks"></p>
<!-- script src="script.js"></script -->
3
Answers
The result I came to. I am confused why the return result worked but remembered i needed it from past lessons, i googled the
A couple of issues in play:
1. Your
labels
variable is a copy of innerHTML’s value, not a reference to it.Your
labels
variable is not a reference to the source element’sinnerHTML
. It is a copy of its value at the time you assigned it. So changing the value oflabels
does not affect the source element in any way whatsoever.If you want to update the element’s innerHTML you must assign it directly. (There are other ways to do this, but for the purposes of this question I’m focusing on what OP is trying to do.)
2. You loop over the array to log them, then return
undefined
.The reason your
console.log(labels);
call emitsundefined
is because yourfor
loop advancesb
until it’s the length of the array, and then you returnmyLibrary[b]
.Javascript arrays are zero-indexed, meaning the first item is
n[0]
and the last item is atn[length - 1]
.Because your
b
variable is equal tomyLibrary.length
when your for loop exits,myLibrary[b]
isundefined
, so that’s what you see in the log.