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 JavaScript Arrays Multidimensional Arrays Improve the Quiz – One Solution

Micah Angelica Baguio
Micah Angelica Baguio
3,409 Points

Improve the quiz - one solution

It keeps saying this: uncaught TypeError: incorrect.push is not a function at quiz.js:34:18 But that's exactly what the teacher did. I just don't understand why his works and mine doesn't?

const questions = [
  ['What is the nearest planet towards the Sun?', 'Mercury'],
  ['What is the second nearest planet towards the sun?', 'Venus'],
  ['What is the third nearest planet towards the sun?', 'Earth'],
  ['Name of the planet next to planet Earth', 'Mars']

]; 


// 1. Create a multidimensional array to hold quiz questions and answers


// 2. Store the number of questions answered correctly
const correct = 0;
const incorrect = 0;
let correctAnswers = 0;

/* 
  3. Use a loop to cycle through each question
      - Present each question to the user
      - Compare the user's response to answer in the array
      - If the response matches the answer, the number of correctly
        answered questions increments by 1
*/
for ( let i = 0; i < questions.length; i++ ) {   
  let question =  questions[i] [0];
     let answer = questions[i] [1];
     let response = prompt(question);

     if ( response === answer ) {
       correctAnswers++;
       correct.push(questions);
     } else {
       incorrect.push(questions);
     }
}

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;
}

// 4. Display the number of correct answers to the user

let html = `
  <h1>You got ${correctAnswers} question(s) correct</h1>
  <h2>You got these questions right:</h2>
  <ol>${ createListItems(correct) }</ol>

  <h2>You got these questions wrong:</h2>
  <ol>${ createListItems(incorrect) }</ol>
`;

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

1 Answer

Steven Parker
Steven Parker
231,275 Points

The push method only exists on arrays, and in the video the variable incorrect is created as an array:

const incorrect = [];

But in this code, it is created as number:

const incorrect = 0;