How to make a CLI Quiz App using Javascript for Beginners
Tags: javascript, cli, quizapp, beginners
Published: 2020-12-04 10:44:52

In this Blog, we will understand how to make a CLI Quiz App using Javascript. 

I’m using JavaScript because is one of the most used programming language today… that’s the 1st reason. The 2nd reason is that I find it really fun to work. But don’t worry if you haven’t used it as I’m going to explain step by step the entire process

For those who don't know what is a **CLI App**:

**Command Line Interface (CLI)**, is a **text-based interface** used to interact with the operating system or the software by typing commands into the interface and receiving a response in the same way that is entirely through your terminal and shell. CLI Applications or (CLIs) they have no graphics or visual interface like GUI Applications.

Also, kindly note that I don’t claim to have the best possible solution. I’m more than happy to see other solutions as well. 

Ok, enough with the chit-chat … let’s get our hands dirty.

## **CLI Quiz App**

Things we will do in this App: 

1. **Ask User to enter their name.**
2. **Tell them the rules and instruction of you quiz**
3. **Ask them questions serialvise**
4. **If the User's answer is right increase their score, and display the score**
5. **If the User's answer is wrong Sshow them the right answer, and decrease the score also don't decrement till negative number (after zero)**
6. **After all question are completed show them the final score**

Great… sounds fun! Let’s get into it.

There are different ways to take user input in Javascript but to take the User input through console ( command line ) we will require one npm package: [**readline-sync**](https://www.npmjs.com/package/readline-sync). 

Firstly, We will import the readline-sync package in our program. To include it,  we use the `require()` function with the name of the module and will store it in a constant variable because it won't change throughout our program:

```jsx
const readlineSync = require('readline-sync');
```

After that, we will greet the user and will ask their name by using `readlineSync.question()` function from our imported pakage and then store the username in a variable for further use :

```jsx
console.log('Welcome to the Quiz');
let username = readlineSync.question("What's your Name: \n");
```

Here, we are concatenation three String. There are different ways to concatenate string in JS , we will use a plus operator to do so! 

```jsx
console.log('Hello ' + username + ", Let's Play the Quiz!!");
```

If you want to have a look at different ways of concatenating string in Javascript [here's it](https://masteringjs.io/tutorials/fundamentals/string-concat).

Now, we will simply display our rules and instructions for our program. Choose any topic you want for your Quiz. Also, note that we are going to ask user both one-word as well as Multiple Choice (MCQ's) questions. 

```jsx
console.log('Rules & Instructions: ');
console.log('1.',username + ', There are 10 Questions on India and all are Compulsory.');
console.log('2. You will get 2 points on each Right Answer.');
console.log('3. One Point will be deducted if the Answer is Wrong.');
console.log('4. In MCQ based questions you have to type the Serial Number / Index Value.');
```

### Now, The Main Logic Begins:

First, we’ll need a variable to store the score of user. We’ll initialize it with 0.

```jsx
let score = 0;
```

We will ask user 5 answer in one word questions and 5 MCQ based questions. For that we will require **2 for loops**, **2 functions** one for MCQ based another for one for one-word answer and **2 array of objects** to store questions and answers.

It you don't know what all these keywords are [here's an article](https://dev.to/prerana1821/core-concepts-of-programming-through-javascript-3dmi) for you.

Let's start with storing an array of object for questions and answers. 

For One-word Questions:

```jsx
var questionsList = [ 
	{
		question : 'India\'s Largest City by Population: ',
		answer : 'Mumbai',
	},
  {
    question : 'National Song of India: ',
    answer : 'Vande Mataram',
  }, 
  {
    question : 'National Motto of India: ',
    answer : 'Satyameva Jayate',
  }, 
  {
    question : 'Golden Temple is situated in: ',
    answer : 'Amritsar',
  },
];
```

For MCQ Questions array we will also store array of Options in it.  

```jsx
var mcqList = [
  {
    array : ['Mumbai', 'Hyderabad', 'Guragon', 'Bangalore'],
    question : 'Which City is known as "Electronic City of India"? ',
    answer : 'Bangalore'
  },
  {
    array : ['Kerala', 'Madras', 'Bangalore', 'New Delhi'],
    question : 'The Indian Institute of Science is located at ',
    answer : 'Bangalore'
  },
  {
    array : ['Dugong', 'Blue whale', 'River Dolphin', 'Pygmy Killer Whale'],
    question : 'What is the name of India\'s National Aquactic Animal: ',
    answer : 'River Dolphin'
  },
  {
    array : ['New Delhi', 'Hyderabad', 'Amritsar', 'Mumbai'],
    question : 'The Centre for Cellular and Molecular Biology in India is situated at: ',
    answer : 'Hyderabad'
  },
  {
    array : ['Delhi', 'Dehradun', 'Lucknow', 'Gandhinagar'],
    question : 'National Institute of Aeronautical Engineering is located at ',
    answer : 'Delhi'
  },
  {
    array : ['T.N.Kaul', 'J.R.D. Tata', 'Nani Palkhivala', 'Khushwant Singh'],
    question : 'Who wrote the famous book - "We the people"? ',
    answer : 'Nani Palkhivala'
  },
];
```

Now, we require function to display question, take user input, check whether the input the correct and on based on that we will increment and decrement the score of the user.

So, Let's start by declaring a function for one-word answers. Also,this function will take 2 inputs question and answer from our array `questionsList`.

```jsx
function quiz(question,answer){}
```

Now, we need a way to display the question to the user as well as take the user given answer for the question displayed. So, again for that we will use `readlineSync.question()` function.

```jsx
function quiz(question,answer){
	let userAnswer = readlineSync.question(question);
}
```

Here, we are displaying the question to the user and then storing the user input in a variable `userAnswer`.

Now we will check whether the user entered answer and our answer is correct or not and depending on that we will increment the score by 2 or decrement the score by 1. Also, remember if the user enters wrong answer we have to display them the correct answer.

```jsx
function quiz(question,answer){
	let userAnswer = readlineSync.question(question);

	if(userAnswer.toLowerCase() == answer.toLowerCase()){
    console.log('You are Right.');
    score = score + 2;
  } else{
    console.log('You are Wrong.');
    console.log('The Correct Answer is:',answer);
    score = score - 1;
  }
}
```

Here, we are converting both answers to lowercase because JavaScript is a **case sensitive** language. It means that "Mumbai" and "mumbai" are two different words. 

If you want to read more about `toLowerCase()` function here are the [docs](https://www.w3schools.com/jsref/jsref_tolowercase.asp).

To display the score after every question we will use `console.log()` after if else condition so that even if either of the conditions run our score will be displayed.

```jsx
function quiz(question,answer){
	let userAnswer = readlineSync.question(question);

	if(userAnswer.toLowerCase() == answer.toLowerCase()){
    console.log('You are Right.');
    score = score + 2;
  } else{
    console.log('You are Wrong.');
    console.log('The Correct Answer is:',answer);
    score = score - 1;
  }
	if(score < 0){
    score = 0;
  }
	 console.log('Score is: ',score);
}
```

We don't know what are scope to decrement below zero (negative number) that's why we are checking wheather `score < 0` .

Function for MCQ questions.

```jsx
function quizMcq(listOfAnswers,question,answer){}
```

You are we will take three inputs for the function. An array of list of option for displaying the options to the user, question and the correct answer to check whether the user entered answer and our answer is correct or not.

Now, We will use one another function from our readline-sync package that is `readlineSync.keyInSelect()` .This function will take two parameters, the list of options to display it to the user and the question. If you want to read more about this function in the docs.

```jsx
function quizMcq(listOfAnswers,question,answer){
	let userAnswer = readlineSync.keyInSelect(listOfAnswers, question);
}
```

Now we will put `userAnswer` in a array of options to check whether entered answer is correct. Rest of all is same.

```jsx
function quizMcq(listOfAnswers,question,answer){
	let userAnswer = readlineSync.keyInSelect(listOfAnswers, question);

	if(listOfAnswers[userAnswer] === answer){
    console.log('You are Right.');
    score = score + 2;
  }else{
    console.log('You are Wrong.');
    console.log('The Correct Answer is: ',answer);
    score = score - 1;
  }
  
  if(score < 0){
    score = 0;
  }
  console.log(chalk.cyan('Score is: ',score));
}
```

Now, we require a for loop to look through our `questionsList` for one-word questions.  

```jsx
for(var i = 0;i<questionsList.length;i++){}
```

Now we will call our `quiz` function in the for loop so that we can repeatedly loop through our questions till the end.

```jsx
for(var i = 0;i<questionsList.length;i++){
	quiz(questionsList[i].question,questionsList[i].answer);
}
```

Understand that, our list of question is an array of **object** that's why we are accessing our object property i.e. question and answer with the dot operator.

 for loop to look through our `questionsList` for MCQ questions. 

```jsx
for(var i = 0;i < mcqList.length; i++) {
  quizMcq(mcqList[i].array,mcqList[i].question,mcqList[i].answer);
}
```

Now finally at the end we will display the total score to the user.

```jsx
console.log('Congratulations,',username,'your Total Score is: ',score);
```

Hurray! We did it!

## Complete Program:

```jsx
const readlineSync = require('readline-sync');

console.log('Welcome to the Quiz');
let username = readlineSync.question("What's your Name: \n");
console.log('Hello',username,", Let's Play the Quiz!!");

console.log('\n');
console.log('Rules & Instructions: ');
console.log('1.',username + ', There are 10 Questions on India and all are Compulsory.');
console.log('2. You will get 2 points on each Right Answer.');
console.log('3. One Point will be deducted if the Answer is Wrong.');
console.log('4. In MCQ based questions you have to type the Serial Number / Index Value.');
console.log('\n');

var questionsList = [
  {
    question : 'India\'s Largest City by Population: ',
    answer : 'Mumbai',
  },
  {
    question : 'National Song of India: ',
    answer : 'Vande Mataram',
  }, 
  {
    question : 'National Motto of India: ',
    answer : 'Satyameva Jayate',
  }, 
  {
    question : 'Golden Temple is situated in: ',
    answer : 'Amritsar',
  },
];

var mcqList = [

  {
    array : ['Mumbai', 'Hyderabad', 'Guragon', 'Bangalore'],
    question : 'Which City is known as "Electronic City of India"? ',
    answer : 'Bangalore'
  },
  {
    array : ['Kerala', 'Madras', 'Bangalore', 'New Delhi'],
    question : 'The Indian Institute of Science is located at ',
    answer : 'Bangalore'
  },
  {
    array : ['Dugong', 'Blue whale', 'River Dolphin', 'Pygmy Killer Whale'],
    question : 'What is the name of India\'s National Aquactic Animal: ',
    answer : 'River Dolphin'
  },
  {
    array : ['New Delhi', 'Hyderabad', 'Amritsar', 'Mumbai'],
    question : 'The Centre for Cellular and Molecular Biology in India is situated at: ',
    answer : 'Hyderabad'
  },
  {
    array : ['Delhi', 'Dehradun', 'Lucknow', 'Gandhinagar'],
    question : 'National Institute of Aeronautical Engineering is located at ',
    answer : 'Delhi'
  },
  {
    array : ['T.N.Kaul', 'J.R.D. Tata', 'Nani Palkhivala', 'Khushwant Singh'],
    question : 'Who wrote the famous book - "We the people"? ',
    answer : 'Nani Palkhivala'
  },
];

let score = 0;
function quiz(question,answer){
  let userAnswer = readlineSync.question(question);

  if(userAnswer.toLowerCase() == answer.toLowerCase()){
    console.log('You are Right.');
    score = score + 2;
  } else{
    console.log('You are Wrong.');
    console.log('The Correct Answer is:',answer);
    score = score - 1;
  }

  if(score < 0){
    score = 0;
  }
  console.log(chalk.cyan('Score is: ',score));
}

function quizMcq(listOfAnswers,question,answer){
  let userAnswer = readlineSync.keyInSelect(listOfAnswers, question);
  console.log('\n');
  if(listOfAnswers[userAnswer] === answer){
    console.log('You are Right.');
    score = score + 2;
  } else{
    console.log('You are Wrong.');
    console.log('The Correct Answer is: ',answer);
    score = score - 1;
  }
  
  if(score < 0){
    score = 0;
  }
  console.log('Score is: ',score);
}

for(var i = 0;i<questionsList.length;i++){
  console.log('\n');
  quiz(questionsList[i].question,questionsList[i].answer);
  console.log('*******************************');
}

for(var i = 0;i < mcqList.length; i++){
  console.log('\n');
  quizMcq(mcqList[i].array,mcqList[i].question,mcqList[i].answer);
  console.log('*******************************');
}

console.log('\n');
console.log('Congratulations,',username,'your Total Score is: ',score));

```

### **Things you will learned while building this app:**

1. **How to take user inputs through an npm module.** 
2. **How to concatenate strings.** 
3. **What are of array of objects and how to loop through them.** 
4. **How to use functions and branching conditions.**

### **Conclusion**

I know that the problem might seem trivial for some of you, but if it helped you in any way, I’m very happy about it!

Thank you very much for the patience. I’d love to hear your feedback about the post. Let me know what you think about this article, and javascript in general, through my [Twitter](https://twitter.com/NawarPrerana) and [LinkedIn](https://www.linkedin.com/in/prerana-nawar-4890b41ab/) handles. I would love to connect with you out there!

**Peace!**