Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Tsipporah Christopher
seal-mask
.a{fill-rule:evenodd;}techdegree
Tsipporah Christopher
Full Stack JavaScript Techdegree Student 6,389 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
217,573 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
Tsipporah Christopher
Full Stack JavaScript Techdegree Student 6,389 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
217,573 Points

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