Joe Consterdine Joe Consterdine - 1 year ago 68
Javascript Question

How does this array work?

just following a simple javascript quiz. The code below works but I have a few questions about it.

var player = prompt("Hello, welcome to the quiz, what is your name?");
var score = 0;

var questions = [
["What is my name?", "Joe"],
["What is my age?", 27],
["What is my favourite sport?", "Football"],
["What is my job?", "Web Developer"],
["What is my eye color?", "Blue"]

function askQuestions(question) {
var answer = prompt(question[0],'');
if(answer === question[1]) {
} else {

for(var i= 0; i < questions.length; i++) {

So the first thing I don't understand is in the askQuestions function the prompt has 'questions[0]'. I know we have a loop but this isn't part of the loop right? So surely this variable is just storing the first array in the questions variable.

The second argument is an empty string ''. Does this just store the answer? How does that work?

I understand rest just having problems with the function.

If someone could explain that would be great!


Answer Source

var questions is an array of arrays of 2D, and each of those 2D-arrays are passed in the loop to askQuestion. Then, for example, When you are passing question[0] to askQuestion at the first loop, you're really passing object ['What is my name','Joe']

Inside function askQuestion you'll pick up then first element of parameter array (so, 'What is my name'), and compare answer with second one element of parameter array (so, 'Joe')

Perhaps if you wrote askQuestion this way you will understand more the workflow :

function askQuestions(**paramArray**) {
  var answer = prompt(**paramArray**[0],'');
  if(answer === **paramArray**[1]) {
  } else {

About prompt, second parameter it's just the default text to show.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download