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

Anthony McCormick
Anthony McCormick
6,774 Points

Code review and toLowerCase() on Arrays?

I have been able to complete this test (it was actually really hard and took a while to get going!). It'd be great if someone could review my code. Please see it below:-

function print(message) {
  document.write(message);
}
var qa = [ 
    ['Who directed Full Metal Jacket, Eyes Wide Shut & 2001: A Space Odyssey?', 'Kubrick'],
    ['Who directed Rear Window, The 39 Steps and Marnie?', 'Hitchcock'],
    ['Who directed Through A Glass Darkly, Seventh Seal and Persona?', 'Bergman']
];
var correctQuestions = [];
var incorrectQuestions = [];


function askQuestion() {
  for (var i = 0; i < qa.length; i++) {
      answer = prompt(qa[i][0]);
      // answer = answer.toLowerCase();
      if (answer === qa[i][1]) {
        alert("Correct!");
        correctQuestions.push(qa[i][0]);
      } else {
        alert("Incorrect!");
        incorrectQuestions.push(qa[i][0]);
      }
  }
}

askQuestion()

print('<h1> Your score is ' + correctQuestions.length + '.</h1><br><h2>You got these questions correct:</h2>' + correctQuestions.join('<br>'));
print('<h2>You got these questions correct incorrect:</h2>' + incorrectQuestions.join('<br>'));

You may of noticed that my answers are names, thus are capitalised which causes a problem if someone types in the answer with a lower case. I thought .toLowerCase() would resolve this but it doesn't, it simply causes my answers to become incorrect regardless. I have tried it two different ways, see both below:-

answer = prompt(qa[i][0]).toLowerCase;
answer = prompt(qa[i][0]);
answer = answer.toLowerCase();

Any ideas how best to resolve this issue? Thanks in advanced!

2 Answers

akak
akak
29,445 Points

Hi,

Right now every answer will be wrong because if someone writes Kubrick by toLowerCase you make his answer kubrick. So it's not expected Kubrick.

Either write answers in your array in all lowercase or make

if (answer.toLowerCase() === qa[i][1].toLowerCase()) 

then kubrick === kubrick

Anthony McCormick
Anthony McCormick
6,774 Points

Thanks for that Akak! Looks like applying the .toLowerCase() in the if statement allows me to enter both Kubrick and kubrick.