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

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!