Absolute Beginner's Workshop: Episode 3 - Arrays, Functions and Shuffling Questions
In the last episode, we dived into the world of JavaScript, learned some basic concepts, and started making our quiz app interactive. Today, we're going to introduce a new concept - arrays - and use it to add more questions to our quiz. Ready to continue our coding journey? Let's go!
What is an Array?
Before we dive into the code, let's understand what an array is. In simple terms, an array is like a list. It can hold multiple values, and each value has a position in the list, known as its index. Think of it as a row of numbered lockers, where each locker can hold something different, and we use the number to access what's inside.
In JavaScript, we can create an array using square brackets []
. Here's an example:
let fruits = ['apple', 'banana', 'cherry'];
In this array, 'apple' is at index 0, 'banana' is at index 1, and 'cherry' is at index 2. Yes, we start counting at 0 in the world of programming!
Arrays are incredibly useful for storing and working with a collection of items. Now, let's see how we can use them in our quiz app.
Step 1: Creating Our Questions Array
First, we need to create an array to hold our questions. Each question will be a string (a sequence of characters), and we'll separate them with commas:
const questions = [
"What is the highest mountain in the world?",
"Who composed the Four Seasons?",
"Which element is denoted by the chemical symbol 'O'?",
"Who wrote 'Pride and Prejudice'?",
"In which year was the World Wide Web invented?"
];
Great job! You've created an array of questions. Now, let's use this array in our quiz.
Step 2: Displaying a Random Question
Instead of displaying the same question every time, we want to make our quiz more interesting by displaying a random question from our array. We can do this with the help of JavaScript's built-in Math.random()
function.
First, we need to calculate a random index. An index in our case can be any whole number from 0 (the position of the first question) to 4 (the position of the last question).
Here's how we can calculate a random index:
let randomIndex = Math.floor(Math.random() * questions.length);
Math.random()
gives us a random decimal number between 0 (inclusive) and 1 (exclusive). We multiply it by the length of our array (questions.length
, which is 5) to get a number between 0 and 5. But because Math.random()
can never be 1, the highest number we can get is 4.999... (which is exactly what we want, as our highest index is 4!).
However, we want a whole number, not a decimal. That's why we use Math.floor()
which rounds down to the nearest whole number. So, 4.999... becomes 4.
Now that we have a random index, we can use it to pick a random question from our array:
let randomQuestion = questions[randomIndex];
In the next step, we'll show this question to the user.
Step 3: Introducing the startQuiz Function
So far, we have set up our development environment and learned about the basics of JavaScript and arrays. Now, let's dive a bit deeper. We will create a function to start our quiz. This function will use our questions array and display the questions in a random order.
First, let's talk about what a function is. In JavaScript, a function is a block of code designed to perform a particular task. It is executed when it's called or invoked. Functions are a fundamental building block of JavaScript and are very useful for code organization and reusability.
Now, let's create a function called startQuiz()
.
function startQuiz() {
// Our code will go here
}
This is a basic function declaration in JavaScript. We define a function with the keyword function
followed by the name of the function (in this case, startQuiz
). The parentheses ()
are used to pass parameters or arguments into the function. Since we don't need any arguments for our function, we leave it empty. The curly braces {}
contain the code that will be executed when the function is called.
Step 4: Randomizing Our Questions
In order to make the quiz more interesting, we want the questions to appear in a random order every time we start the quiz. For that, we need to shuffle our questions
array.
Shuffling an array in JavaScript can be done using various methods, but a popular and reliable way to do it is using the Fisher-Yates (also known as Knuth) shuffle algorithm. Here is the shuffle function using this algorithm:
function shuffle(array) {
for(let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]]; // Swap elements
}
}
Now we will shuffle our questions
array in the startQuiz
function and then display each question one by one:
function startQuiz() {
// Shuffle the questions
shuffle(questions);
// Loop through each question
for (let i = 0; i < questions.length; i++) {
let currentQuestion = questions[i];
let userAnswer = readline.question(currentQuestion + '\n');
console.log("You answered: " + userAnswer);
}
}
Here's what we've done:
- We've shuffled our questions array to ensure the order is random.
- Then we've looped through each question in the shuffled array.
- For each question, we've asked it to the user and logged their answer to the console.
Step 5: Reviewing the Complete Code
Before we proceed, let's take a look at our complete code so far:
// Import the readline module
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
// Create an array of questions
const questions = [
"What is the highest mountain in the world?",
"Who composed the Four Seasons?",
"Which element is denoted by the chemical symbol 'O'?",
"Who wrote 'Pride and Prejudice'?",
"In which year was the World Wide Web invented?"
];
// Shuffle function
function shuffle(array) {
for(let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
// Start quiz function
function startQuiz() {
// Shuffle the questions
shuffle(questions);
// Loop through each question
for (let i = 0; i < questions.length; i++) {
let currentQuestion = questions[i];
console.log("Question: " + currentQuestion);
}
}
// Call the startQuiz function
startQuiz();
Step 6: Running Our Program
We have now updated our quiz function to include a wider range of questions and display them in a random order. It's time to see it in action!
In your terminal, type the command node quiz.js
and hit enter. You should see one of your questions appear on the screen. If you run the program a few times, you'll notice the questions change order - this is the power of randomness in action!

Recap
Congratulations on reaching the end of Episode 3! You've now learned about functions and arrays in JavaScript, how to shuffle an array, and how to loop through array items. These are significant steps in your journey to becoming a confident coder. Stay tuned for the next episode, where we'll add even more interactivity to our quiz!
Every like, share, and comment brings more coding enthusiasts into our community, and that's what makes this journey even more exciting.
Cheers!
Comments ()