I’m closer than I ever have been to understanding core principles of programming.  But the best way of learning is to keep practicing with as many real life scenarios as possible. Which is why it can get disheartening when I try to write code from scratch and find myself experiencing what can  I can only describe as the programmers equivalent of writer’s block.

As if the right solution (or solutions) are wiped from my brain and I don’t know what to do next.

I’m also a dyslexic thinker so I have a preferred way of taking in instructions and information.  I’m far more successful at reading code that’s been provided and understanding what is going on then writing some code on the fly.

I keep telling myself it’ll come, in time. And I’m sure with the hours I put in that’ll be the case.  But enough of me and my dyspraxic brain.  Here’s another script and my summary of what I think is going on.  Though I say it myself, I think it shows some progression of knowledge of how a simple script could be put together.

We’re Iterating again

First, all the arrays and variables used in the script are organised at the top of the script. It’s common programming practice and keeps a script file organised.

One Array holds the questions and answers; two empty arrays with will be used to identify the questions answered correctly and those answered incorrectly.

CorrectAnswers is assigned a number and counts how many questions were answered correctly.

Then there are variables assigned that wll eventually be used to store HTML strings and assign methods to populate our empty arrays.

var questions = [
[‘How many states are in the United States?’, 50],
[‘How many continents are there?’, 7],
[‘How many legs does an insect have?’, 6]
];

var correct=[];
var wrong=[];

var correctAnswers = 0;
var question;
var answer;
var response;

The print function provides a method to display items to the screen other than document.write. By locking on to a specific element we can control where the output appears on the screen. message is enclosed in parentheses and is a placeholder variable and is given a value with a function call so it will be used later on.

function print(message) {
var outputDiv = document.getElementById(‘output’);
outputDiv.innerHTML = message;
}

buildList is the function that creates a string of a HTML list element and it’s list items. using “arr” as a parameter, arrays are passed in later on in the script; arrays that determine if the value passed in is a question that has been answered correctly or incorrectly.

This is clever because arr[i] is a placeholder yet the script knows that the value will be an array to iterate through using the loop.

function buildList(arr) {
var listHTML = ‘<ol>’;
var listHTML = ‘<ol>’;
for(i=0; i<arr.length; i+=1) {
listHTML += ‘<li>’ + arr[i] + ‘</li>’;
}

listHTML += ‘</ol>’;
return listHTML;
}

This next piece of code is the loop that performs the iteration through the initial questions Array. It has 2 main jobs. Firstly, to loop through question giving the opportunity for the user to give an answer to each question, and to count the number of correct answers.

A condition statement looks for the value each time the loop iterates and if the value given is the same as what is in the answers part of the questions array, 1 is added to the value in correct answers.

for (var i = 0; i < questions.length; i += 1) {
question = questions[i][0];
answer = questions[i][1];
response = prompt(question);
response = parseInt(response);
if (response === answer) {
correctAnswers += 1;
correct.push(question);
} else {
wrong.push(question);
}
}

Output the details by combining strings and displaying them to the screen. It outputs the value of the correctAnswers array, and depending on the answer adds displays the contents of the correct and wrong array in HTML list items. buildList function can tell the difference because the values passed into them in buildList(correct) are n fact arrays with values in them. Once all the array values have been seen, the script moves on.

Each new line of code adds more values to the same HTML by using +=

html = “You got ” + correctAnswers + ” question(s) right.”;
html += “<h2>You got these questions correct: </h2>”;
html += buildList(correct);
html += “<h2>You got these questions wrong:</h2>”;
html += buildList(wrong);

This passes the string that was created above into the print function. It uses the parameter message to output the HTML to the screen to the element with the id #output.
print(html);

Conclusion

There are several programming techniques at play here.

  • Tracking data using variables.
  • Passing arguments into functions
  • Iterating through array values using loops

Using parameter links functions together and using functions makes scripts, modular, efficient and easy to read and it’s important to get into the habit of using these techniques are they’re all very common in JavaScript programming.

Advertisements

The “Iteration” Game

In my latest blog, I wanted to talk about iteration in Loops and how they can be and are combined with Arrays in programming, with a particular emphasis on JavaScript.

Loops are commonly used in programming to simplify repetitive task such as looping through a list of names or looping through a list of game scores so the highest can be found.

But first you need a way of storing that data.  You could do that with a list of multiple variables.

var Name1 = “Darren”
var Name2 = “James”
var Name3 = “Nick”

But this is messy, code intensive and very difficult to maintain. There must surely be a better way to store multiple items of data.

That is where the array comes in.  With an array you can store the above names in one line of Code.  We start with the var keyword, give the Array a name and finally assign the values in what is called an array literal [].

var namesList = [‘Darren’,’James’,’Nick’]

So there’s our list, in a nicely stored list of values.  They names are each given an array index which is the programming way of assigning a place for them to be accessed.  “Darren” is in the array index of [0]. James is in the array index of [1] and so on.

But now that we’ve got our nicely organised list of values, what do we then do with it?

Well we can either access the values individually with

console.log(namesList[0]);

Which would output Darren to the console.

Or we can do something a little more useful and output the contents to the screen.  Which sounds exciting. But what if we added more values to the array.  How on earth would we keep track of how many items are now in the array?

Luckily JavaScript has a handy method which counts the length or the number of values in our array. And  we can use this in a process called Iteration.

We’ve already said that Arrays can be combined with loops.

function displayNames(namesList) {
var listHTML = ‘<ol>’;
for(var i=0 i <namesList.length; i+=1) {

listHTML += ‘<li>’ + list[i] + ‘</li>’;

}
listHTML += ‘</li>’
print(listHTML);
}

displayNames(namesList);

What the above shows is a loop inside a function which has an array passed into this function as parameter.  What does that mean?  It basically means we’ve taken our Array and given this Array and its data to the function displayNames. Now we can do something with the data.

In this function we’ve declared 2 new variables.

In listHTML we’re going to write HTML output to the screen including the elements and their values.  We can start by simply using one simple statement to write the opening ordered list tag.

The next job is a little more complicated. We need to print as many list items as there are items in the array.  If we knew how many were in we could probably just write something like

listHTML += ‘<li>’ + list[0] +'</li>’;
listHTML += ‘<li>’ + list[1] + ‘</li>’;
listHTML += ‘<li>’ + list[2] + ‘</li>’;

to write out each individual value.  But it’s not dynamic enough, it involves repeating too much code and to get the code to work, you’d have to add more of these lines as you add more items to the array.

Fortunately the loop offers a good way to simplify this code.

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

A second variable acts as a counter variable which we then use to count the values in the namesList array but only for as many times as there are values. That’s the job of namesList.length. We can use this to replace the need to put in a finite number. Now, however many values we have will there will always be enough numbers in the condition go through the whole array.

listHTML += ‘<li>’ + list[i] + ‘</li>’;

Now this is the crucial bit. This is where we play the iteration game.  Where we once put an array index in the array literal brackets [i] We now put in our counter variable.  This alllows us to iterate or go through all the array values and perform actions on them.

Using a series of strings of text grouped (or concatenated) together we’re putting together a HTML list item tag, as many times as there are values in the namesList array.  list[i] is the way that JavaScript tells the difference between each item in the array.

    listHTML += ‘</ol>’;
displayNames(listHTML);
}

Finally the list item is closed in another addition to the listHTML variable. We then write the command to print the HTML to the screen.

displayNames(namesList);

But no function runs unless it has been called.  This code above calls the displayNames function with the Array Name argument.

And that is the “Iteration game”. Iteration is the process of cycling through array values in a loop so we can perform actions or calculations on them and is an important and common tool in the skillset of web programmers.