Quiz App with NodeJS for beginners.
Tags: javascript, node, beginners, replit
Published: 2021-08-15 09:09:57

###How to create a quiz app in nodeJS as a beginner? 

NodeJS is a backend platform to run Javascript code in server side and very trendy one too. Today we will build a quiz app where the user can answer question and get their score. 

###What will you learn? 
1. Functions
2. Readline Sync
3. Arrays
4. For loop

###How to start?
To start with this quiz app, you don’t need to install any npm package in your device. The only thing required is internet. Open Repl.it on your device and create your account in it. After that, go to the Create section and find “NodeJS” in the language section and then create repl.

So far, so good. Now you have a terminal where you can write code but you don't know the language yet. So let's start with it. 

Now to our question, to start with creating the web app, we need to first understand what are we creating. A quote by John Johnson for it, 

>“First solve the problem, then write the code.” 

Starting on, to create a quiz app on any topic, there are three features -

Score of the user
Questions of the quiz
Answers to the quiz

We’ll build these step by step by using functions. 

Start with building function.

First, lets import a package called **“readline-sync”**. I know, you’ll think what’s readline sync?

*What is Readline Sync?*

Readline sync is an **inbuilt function provided by nodeJS** that tries to let your script have a conversation with the user via a console. 
Just like our mobile phones have inbuilt apps, even programming languages have inbuilt functions to ease our development. 

So, to import the function from the web, all we have to type is, 

```javascript
var readlineSync = require('readline-sync');
```
To read more about readline-sync, go [here.]
(https://www.npmjs.com/package/readline-sync)

Now, you have stored the inbuilt function as a variable. You have the liberty to use this variable anywhere now. Without doing this, you cannot create the quiz app. 

Since NodeJS is a backend langauge, anything we want to print on the screen of user, will be printed by using **console.log()** function. Just like Readline-Sync, it's an inbuilt function.

So, to start, let's do a simple small exercise- 

>A program that asks the user their name and then displays a welcome message with their name.

```javascript
var readlineSync = require("readline-sync");

console.log("welcome to MARVEL quiz");

var username = readlineSync.question("Your Name? ");

console.log("Welcome to THE QUIZ, " + username + "!");
```

So, using the *.question* after readline-sync, asks the user a question, which he has to answer. This eases your work. 

Good job after completing the starting exercise. 

Now, the real coding part. Let's start by building a question and answer function which later through loop will ask questions automatically. 

So first we need a database which will contain questions and their answers. 

```javascript
var questions = [
  {question:"how many iron man suits did tony stark create in the cinematic universe? ",
  answer:"85"},
  {question:"Name of Thor's original hammer",
  answer:"mjolnir"},
  {question:"Where was Mjolnir forged?",
  answer:"Nidavellir"},
  {question:"Father of the God of Thunder",
  answer:"Odin"},
  {question:"Who is the god of mischief?",
  answer:"Loki"},
  {question:"Did you like the quiz?",
  answer:"yes"}
  
``` 
The above program is a dictionary with a **key: value** pair. 
So the question and answer are the keys, whereas the content in the double-quotes("") is the value of the key. 

The square-brackets([]) declare the following content as an array, which makes it easy for the program to run through the content. *Your database is in form of an Array. A array is simply a way to represent data in a collection.*

The basic syntax is, 
```javascript
var name_of_the_variable = [{key: value}, {key: value}]
```

The comma(,) seperates the two elements. 

>Tip : You can name the variable anything but it's a better practice to name it to somethinng relevant to the content inside the var.

Now the loop of the questions. How are you gonna continuously show the user your questions?

A little loop for that is- 
```javascript
for(var i=0; i<questions.length; i++){
  var currentq = questions[i];
  quiz(currentq.question, currentq.answer);
}
```
This loop automatically displays the next question after the user has answered the previous one. 

Don't get overwhelmed. Let me explain the loop to you.
```javascript
for(var i=0; i<questions.length; i++)
```
The for here, says that the loop is a 'for' loop. There are different types of loops.

>You can read the detailed version about them [here.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)

The content inside the parentheses are the condition in which the loop has to be executed/start. 

> One of the confusions to avoid while writing a program is understanding the difference between parameters in functions and global variables. I'll soon write a blog about it.

So, back to the conditions, the *(i=0; i < questions.length; i++)*. 'i' here is an initial value passed in the loop. So when we say *i=0*, we are declaring the value of i is 0. 

i < questions.length means the value of i is less than the length of questions. 

>You can read more about the array functions [here.] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)

and finally, i++ means that the questions have to increase after the user has answered. 

i++ simply means i = i + 1, i.e. , the value of i is increased by 1.

Now, lets move onto the {} part of the loop-
 ```javascript
for(var i=0; i<questions.length; i++){
  var currentq = questions[i];
  quiz(currentq.question, currentq.answer);
}
```

Here we declare a variable called currentq qhich displays the current question that the user is implementing. The value assigned to the variable is used from the loop.

Warning! quiz here is not an inbuilt function.  We are about to develop it - 
```javascript
var score = 0;
function quiz(question, answer){
  var userAnswer = readlineSync.question(question);
  if(userAnswer == answer){
    console.log("correct! ");
    score++;
  }
  else{
    console.log("wrong! ");
    score--;
  }
  console.log("your score is ",score);

// For neatness
  console.log("-------------------");
}
}
```

This is the most important part of the program. Here, all the implemetation of the program we have written so far.

We start by declaring a variable score which will be the score of the user after he answers the question.

The function quiz takes in 2 parameters, question and an answer.

Since there are only two outputs for the a question. We will use the conditional statement if()...else. 

So, *if* the userAnswer is equal to the correct answer, then we will show the output as "Correct!" And increment the score of the user. 

If the userAnswer is not Equal to the correct answer,  the output will be a "Wrong!" and the score will decrease.

In both conditions, after the user has answered the question, his score will be shown.   

Your Final Program should look like this- 
```javascript
var readlineSync = require("readline-sync");

console.log("welcome to F.R.I.E.N.D.S. quiz");

//this is line breaker, like it leaves a line.
console.log("\n");


var username = readlineSync.question("Your Name? ");

console.log("\n");

console.log("Welcome to THE QUIZ, " + username + "!");

var score = 0;
function quiz(question, answer){
  var userAnswer = readlineSync.question(question);
  if(userAnswer == answer){
    console.log("correct! ");
    score++;
  }
  else{
    console.log("wrong! ");
    score--;
  }
  console.log("your score is ",score);
  console.log("-------------------");
}

//questions
var questions = [
  {question:"how many iron man suits did tony stark create in the cinematic universe? ",
  answer:"85"},
  {question:"Name of Thor's original hammer",
  answer:"mjolnir"},
  {question:"Where was Mjolnir forged?",
  answer:"Nidavellir"},
  {question:"Father of the God of Thunder",
  answer:"Odin"},
  {question:"Who is the god of mischief?",
  answer:"Loki"},
  {question:"Did you like the quiz?",
  answer:"yes"}
];

//LOOP
for(var i=0; i<questions.length; i++){
  var currentq = questions[i];
  quiz(currentq.question, currentq.answer);
}

//To display the final score.
console.log("YOUR FINAL SCORE IS: " + score+"/10")

```

>Explore the world of NodeJS through reading documentations from [MDN docs.](https://developer.mozilla.org/en-US/) and other sources.


If you think there are some errors or a typo in my explanation please write it in the discussion. Happy to help!