DEV Community

Cover image for Mastering The Basics Of JavaScript : Creating a Math Quiz Program
Adibaalotu Alexander
Adibaalotu Alexander

Posted on

Mastering The Basics Of JavaScript : Creating a Math Quiz Program

Imagine the excitement of exploring a new programming language after months of working with Python. As a Python developer, I found myself captivated by the versatility and widespread use of JavaScript in web development. The shift from Python to JavaScript presented an opportunity for growth and expansion of my skill set. In this article, I want to share one of the projects that helped me practice the basics of JavaScript while honing my programming skills.

Introducing the Math Quiz Project

The math quiz project served as a practical exercise to apply my newly acquired JavaScript knowledge while reinforcing the basics. The project aimed to generate random questions; random numbers had to be created within a range; check user's answers after taking their inputs; manipulate strings; and make conditional statements. The objective was to develop a program that could randomly generate math questions, providing an interactive learning experience.
In the next section, I will guide you through the step-by-step process of building the math quiz program. We will examine the key JavaScript functions, discuss the logic behind the code, and explore how the project helps solidify the language's fundamentals.

A STEP-BY-STEP OUTLINE OF WHAT WE WANT FOR THE MATH QUIZ

  1. We need to generate a random number within a range.
  2. We need to generate random questions.
  3. We need to check the user's answer against the correct answer while keeping track of the user's score.

Generating Random Numbers

We need to define a function that generates and returns a random number within a minimum and maximum range.

// GENERATE RANDOM INTEGER

function genRandomInt(min, max){
  const randomNumber = Math.random() * (max + min + 1)
  return Math.floor(randomNumber) + min;
};
Enter fullscreen mode Exit fullscreen mode

ThegenRandomInt() function takes two parameters (min and max) to specify the range we want the random number to fall into. TheMath.random() function in JavaScript is a built-in method that generates a random floating-point number between 0 (inclusive) and 1 (exclusive), i.e., it generates a number between 0 and 1 but not 1. (max - min + 1) represents the range of values we want to generate, including both min and max. The product of Math.random() * (max - min + 1) was stored in the variable randomNumber.
The Math.floor() function is then used to round down the decimal value of the randomNumber to the nearest integer. However, at this point, the range is starting from 0, so in a bid to adjust it, we add the min value to the result. This adjusts the range and makes it start from the min value.

Generating Random Questions

This function doesn't take any parameters. It is used to generate random questions.

// RANDOM QUESTION GENERATOR

function genRandomQuestion() {
  const randomOne = genRandomInt(1, 10) // First random number
  const randomTwo = genRandomInt(1, 10) // Second random number
  const operator = genRandomInt(1, 4)

  let question;
  let answer;

  switch (operator) {
    case 1: // addition
      question = `${randomOne} + ${randomTwo}`;
      answer = randomOne + randomTwo;
      break;

    case 2: // subtraction
      question = `${randomOne} - ${randomTwo}`;
      answer = randomOne - randomTwo;
      break;

    case 3: // multiplication
      question = `${randomOne} * ${randomTwo}`;
      answer = randomOne * randomTwo;
      break;

    case 4: // division
      question = `${randomOne} / ${randomTwo}`;
      answer = randomOne / randomTwo;
      break;

    default: // default case
      question = "Invalid operator";
      answer = null;
      break;
  }
  return {question, answer};

};

Enter fullscreen mode Exit fullscreen mode

Inside the genRandomQuestion() function, we generate two random numbers between 1 and 10 (both inclusive), which will be used to generate the question for users. We use another random number to determine the operator used for the question (1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division). Based on the operator, using template literals, we define the question. After generating the two (2) random numbers(randomOne & randomTwo) and the random operator, we had to use a switch statement, which is used to perform different actions based on different conditions. It provides a concise way to write multiple if...else if...else statements when there are multiple possible cases to consider. The switch statement takes an expression; in this function, the expression taken is the operator, The expression is evaluated and compared with the values specified in the case; clauses. If there's a match, the code block associated with the case; is executed, and the break; statement is used to exit the switch(). It is good practice to have a default block that handles fallbacks if there are unmatched cases.
At the end of the switch statement, we returned an object containing the question and answer, with the answer being the correct one, which we'll compare to the answer provided by the user.

Checking the User's answer

We'll need to write a function that checks if the answer provided by the user is correct or incorrect, and if it is correct, we increase their count.

// USER ANSWER CHECKER

function checkAnswer(userAnswer, correctAnswer, count) {
   if (userAnswer === correctAnswer) {
    console.log('Correct answer!!!');
    count++ ; // increases the count if the user gets the correct answer
   } else { // What happens if the user's answer is wrong?
    console.log('Incorrect answer!!!');
   }

};
Enter fullscreen mode Exit fullscreen mode

The checkAnswer() function takes three parameters (userAnswer, correctAnswer, and count). The if statement was used to check the strict equality (if the operands have the same type and the same value, the expression evaluates to true) of the userAnswer and the correctAnswer. If the answer is correct, the count increases; otherwise, it doesn't.

Main Math's Quiz Program

Here, after writing the other functions, we need to write the main function that will be called for our script to run.

// QUIZ STARTER FUNCTION

function startQuiz() {
  const numberOfQuestions = 10; // number of quiz questions
  let count = 0;

  for (let i=0; i < numberOfQuestions; i++) {
    [question, answer] = genRandomQuestion()
    console.log(`Question $i + 1: ${question}`) // The question is logged for the user.
    response = prompt(`What is your answer?: `);
    const userAnswer = parseFloat(response); //converts string to floating point numb.
    checkAnswer (userAnswer, answer, count)
  }  
  console.log(`Quiz complete, your score is: ${count} out of ${numberOfQuestions}`)

};

// Start THE QUIZ
startQuiz()

Enter fullscreen mode Exit fullscreen mode

After defining the startQuiz() function, we declared a numberOfQuestion variable to indicate the number of questions for the quiz. After that, we used the let keyword to declare the count variable with a starting value of 0, because it gives the count variable a block scope and allows the variable to be manipulated.
We proceed to write a for loop that keeps on running as long as the value of i that started as 0 continues to be less than the numberOfQuestions.

The block of code inside for loop (), calls the genRandomQuestion() function that we defined earlier; this function returns an object that contains the question and answer. After the assignment of the question and answer object[question, answer], we logged the question into the console, asking for the user's response via a prompt.
For this line of code: response = prompt('What is your answer? '); to work, we need to install and import the prompt module if we are not running the code in a browser environment. If you are working with JavaScript in other environments, such as Node.js for server-side JavaScript, the prompt function is not available. In such a case, we will need to use an alternative method to capture user input.
Open the command prompt or terminal in the directory where your project file is located and run the command below:

npm install prompt-sync  // This is used to download the prompt-sync module.
Enter fullscreen mode Exit fullscreen mode

After running this line of code, go to the top of the JavaScript file and declare the variable prompt above all the functions we've written so far.

// Declare this at the top of the script
const prompt = require('prompt-sync')();
Enter fullscreen mode Exit fullscreen mode

After the user responds, the response is parsed into a floating-point number before being passed as a parameter together with the answer and counted into the checkAnswer() function to check if the user input is correct. At the end of the for loop, the User gets to see their score.
The code is executed when the startQuiz() function is called.

Conclusion

In conclusion, the math quiz project has been an invaluable exercise for reinforcing my understanding of JavaScript fundamentals. Through its practical implementation, I successfully applied my knowledge of JavaScript syntax, logic, and functionality. This project provided me with valuable insights into JavaScript's capabilities, allowing me to create dynamic and interactive applications. I look forward to further exploring advanced topics and tackling more complex projects in JavaScript.

Top comments (0)