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

Tsipporah Christopher
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tsipporah Christopher
Full Stack JavaScript Techdegree Graduate 15,593 Points

Getting an undefined before my order list, the first item on the list is blank on the webpage

Hello,

I am having issues with my code. I keep getting and undefined before my ordered list on the webpage.

For example,

Correct Answers:


  1. What color is the sky?
  2. What color is the grass?
  3. What is my hobby?
let correctAnswers = [''];
let incorrectAnswers = [''];


let quiz = [
    ['What is my name?','marie'],
    ['What color is the sky?', 'blue'],
    ['Where do I learn to code?', 'treehouse'],
    ['What color is the grass?', 'green'],
    ['What is my hobby?', 'coding']
  ];


  let correctCounter = 0;


  for (let i = 0; i < quiz.length; i++) {
    let input = prompt(quiz[i][0]); 

    if (input.toLowerCase() === quiz[i][1]) { 
    correctCounter ++; 
    correctAnswers.push( `${quiz[i][0]}` ); 
        } else {
        incorrectAnswers.push(`${quiz[i][0]}`); 
      }
}



let display = (arr) => {
    let list = '';
    for (let i = 0; i < arr.length; i++) {
    list += `<li>${arr[i]}</li>`;
    }
    return list;
};



let html = `<h2>You got <strong>${correctCounter} question(s)</strong> out of 3 correct!</h2><br>

<h2>Correct Answers:</h2> 
<ol>
${display(correctAnswers)}
</ol>
<h2>Incorrect Answers:</h2>
<ol>
${display(incorrectAnswers)}
</ol>
`;


document.querySelector('main').innerHTML = html;

Thank you for your help!

3 Answers

Steven Parker
Steven Parker
231,248 Points

An empty first element is being placed in the array when it is created: let correctAnswers = [''];.

What you probably intended to do was to start with an empty array: let correctAnswers = [];.

Tsipporah Christopher
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tsipporah Christopher
Full Stack JavaScript Techdegree Graduate 15,593 Points

Oh wow! Thank you so much Steven! I understand that now. So the array, I created wasn't actually empty.. it had one element inside it ( it just consisted of a space). Thank you!

Steven Parker
Steven Parker
231,248 Points

Actually, not even a space — it was an empty string (no characters), but it still took the first slot.