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 trialluisgomez7
5,557 PointsI have question about the coding shown in Javascript video title "Create a Multidimensional Array".
In the coding below, why is it necessary to set the variable "items" to ' ' ? Then later in the code, why is it necessary to combine it with "+=" ?
const playlist = [
['So What', 'Miles Davis', '9:04'],
['Respect', 'Aretha Franklin', '2:45'],
['What a Wonderful World', 'Louis Armstrong', '2:21'],
['At Last', 'Ella Fitzgerald', '4:18'],
['Three Little Birds', 'Bob Marley and the Wailers', '3:01'],
['The Way You Look Tonight', 'Frank Sinatra', '3:21']
];
/*const myArtists = `${playlist[0][1]}, ${playlist[1][1]}, ${playlist[5][1]}`;
console.log(myArtists);*/
function createListItems( arr ) {
let items = '';
for ( let i = 0; i < arr.length; i++ ) {
items += `<li>${ arr[i][0] }, by ${ arr[i][1] } - ${ arr[i][2] }</li>`;
}
return items;
}
document.querySelector('main').innerHTML = `
<ol>
${createListItems(playlist)}
</ol>
`;
1 Answer
Jassim Alhatem
20,883 PointsYou set items to ' ' because later on in your function you're adding to it using +=. If you declare the variable without a value, meaning let items;
, and then you add to it, the output will be "undefined" followed by the text that you added.
It's not necessary to combine it with += you can use
items = items + `<li>${ arr[i][0] }, by ${ arr[i][1] } - ${ arr[i][2] }</li>`;
but using += is cleaner.
luisgomez7
5,557 Pointsluisgomez7
5,557 PointsUsing only + instead of += doesn't work. I just tried it. Anyway, I can see now that let items='' is needed to declare "items" as a string value which is then used to create list consisting of artists, their songs and the lengths of their songs which are all string forms of data. Thanks for answering.