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
mrx3
8,742 PointsI don't understand how functions are going to make my code better with less repeating? (codepen included).
Here's my codepen I made, it's also my first function. It's not much but, it's a start. http://codepen.io/mike316/pen/MaaorO
I just started with a bunch of prompt boxes, and added a document.write() function at the end. I plan on making a test like we had to make in section three of JavaScript Basics. Some of ideas I can't wrap my brain around are, how could I add if, else if, and else statements with this, how can add a score variable to keep track of how many answers the user has correct, and how I can do all this without repeating code. The way I'm looking at this program right now, I would still be repeating code like crazy. I would like to know how I can do this program without repeating all that code? I'm new to JavaScript but I'm getting better. Any help with this would be greatly appreciated. Thank you in advance for any help.
3 Answers
LaVaughn Haynes
12,397 PointsJohn is correct in that you can use arrays to store the questions and answers. If you have a simple project, functions might appear to make your code even longer. For bigger projects it will be more obvious why the functions are helpful. For example, if you have a massive quiz and you decide that instead of prompting the user, you want to print the questions to the page. You can easily change your function instead of modifying each question.
There are various ways that you can do what you are trying to do. Here is one example. If you don't understand then feel free to ask questions.
//define questions array
var questions = [
["What programming language is a gem?", "Ruby"],
["What programming language is a reptile?", "Python"]
];
//define answers array
var answers = [];
//define function to ask all of our questions and check answers
function askQuestions(questionsArray) {
//variables
var answersArray = [];
var userAnswer = '';
var correctAnswer = '';
var totalCorrect = 0;
//loop through the questionsArray
for(var i = 0; i < questionsArray.length; i++){
//get answer from user
userAnswer = prompt(questionsArray[i][0]);
//get correct answer from questionsArray
correctAnswer = questionsArray[i][1];
//test answer
if(userAnswer.toLowerCase() === correctAnswer.toLowerCase()){
totalCorrect++;
}
//add users answer to the answersArray
answersArray.push(userAnswer);
}
//return an object containing totalCorrect and answersArray
return {
"total": totalCorrect,
"answers": answersArray
};
}
//define function to print all of our answers
function printAnswers(answersObject){
//get values from the answersObject
var answers = answersObject.answers;
var total = answersObject.total;
//the "join" method turns the array into a string separated
//by the value supplied, which in this case is ', '
document.write('Your answers are ' + answers.join(', ') + '.');
document.write('You got ' + total + ' correct out of ' + answers.length + '!');
}
//run the functions
answers = askQuestions(questions);
printAnswers(answers);
John Renzema
9,070 Pointswhy not put your questions and answers in a 2 dimensional array, and use a for loop to ask the questions. Then if you use a conditional statement ei. if{}else{} inside the for loop you can have different response depending on the answer.
Also your code will be easy to add more questions to, and always remember DRY.
If this just confused you I can do some of the work in an example.
mrx3
8,742 PointsI haven't gotten to loops yet, and I don't even know what a 2 dimensional array is.. :D At least now I know what I should do...even though I don't know how to do it LOL.
John Renzema
9,070 PointsWorking your way through javascript you will quickly learn about for loops and arrays. Both are a huge part, and can be used to do a lot of really interesting stuff.
Enjoy.
mrx3
8,742 Pointsmrx3
8,742 PointsI have not gotten that far with loops and other things in this code. So basically....I don't know what a lot of that "stuff" means in your code, my best bet is to hold out and get a little further in JavaScript journey. Sometimes when I watch the videos I ask myself," What if and how do you do this." and I jump the gun. Thanks for the help though.
LaVaughn Haynes
12,397 PointsLaVaughn Haynes
12,397 PointsI thought it might be a bit complicated. The good news is that most of this stuff is covered in these lessons:
http://teamtreehouse.com/library/javascript-basics
http://teamtreehouse.com/library/javascript-loops-arrays-and-objects
Once you learn loops it will go a long way towards helping you achieve your goal of having less repetition. For example in your pen you have 5 prompts. You can make an array of 5 questions. Create a function that prompts the user with a question that is passed to it. Then make a loop to loop through each item (a question) in the array and pass it to the function.
After you get that down then add an answer checking mechanism. Then maybe tally the score. Constantly build on what you learn.