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 Loops, Arrays and Objects Tracking Multiple Items with Arrays Build a Quiz Challenge, Part 1

Mike Harrison
Mike Harrison
3,147 Points

If my quiz has a mix of integers and strings as answers, how do I go about passing these both through as valid?

Currently, I can only seem to make the quiz work using only all integers as answers, or all strings as answers.. not a mix of the two. If I understand correctly, the parseInt() function converts a string answer to an integer. I have tested this out and set my answers to strings, but no luck. What am I doing wrong?

See my code below:

var questions = [
  ['What is 5 + 5?', '10'],
  ['What is 20 + 10?', '30'],
  ['What is 10 / 2?', '5']
];

var score = 0;
var question;
var answer;
var response;
var correctQuestions = [];
var incorrectQuestions = [];

for ( var i = 0; i < questions.length; i++ ) {
  question = questions[i][0];
  answer = questions[i][1];
  response = parseInt(prompt( question ));
      if ( response === answer ) {
        score ++;
        correctQuestions.push( question );
      } else {
        incorrectQuestions.push( question );
      }
}

document.write( score, correctQuestions );

Ultimately - I would like to know how I would have a mix of both integers and strings as my answers. So something like this:

var questions = [
  ['What is 5 + 5?',  'ten'],
  ['What is 20 + 10?',  30],
  ['What is my name?', 'mike']
];

1 Answer

Justin Iezzi
Justin Iezzi
18,199 Points

Hey Mike,

You can check if something is a number or not by using JavaScript’s isNaN() function.

You could use this in an if/else statement to handle the user's input appropriately.

As for your example, spelling out "ten" and translating that as an answer for "10" or the integer 10 is a much more complicated and somewhat uncommon solution. Assuming that's what you meant.

Let me know if you have more questions. :)

Mike Harrison
Mike Harrison
3,147 Points

That is very useful, thank you!