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

Any suggestions to a simpler way for the inner loop avoiding if, else if, else if?

In this video I stopped it before I got to the point of the solution suggestion because I thought that we were going to solve it using a innerloop looping through song, artist and lenght, to add all the commas, spacings and whatnot, and then an outer loop which would add the <li></li> to end of every element.

After coding it, the solution in the video were simpler but I'm still wondering if anyone can comment on my solution. I was really unsure about using the if, else if, else if to solve the phrasing of the sentences, and I wonder how someone experienced would've solved this.

"[Song], by [Artist] - [Length]"

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']
];

function createListItems(arr) {
  let items = '';
  for (let i = 0; i < arr.length; i++) {
    items += `<li>`;
    for (let j = 0; j < arr[i].length; j++) {
      if (j === 0) {
        items += `${arr[i][j]}, by `;
      } else if (j === 1) {
        items += `${arr[i][j]} - `;
      } else if (j === 2) {
        items += `${arr[i][j]}`;
      }
    }
    items += `</li>`;
  }
  return items;
}

document.querySelector('main').innerHTML = `
  <ol>
    ${createListItems(playlist)}
  </ol>
`;