In this part we'll discuss ALF: Arrays, Loops and Functions, elements that are the heart of any programming language.
I wish to thank Don for making this tutorial use the best language possible - I could not achieve this without you, Don!
First, a quick reminder for those who forgot:
- An array is a collection of items.
- Each item in an array can be anything. (even another array)
- An array can contain as many items as we want.
- We can reference an item in an array by using its index in the array.
- A basic array (and that's what we're going to discuss) does not support removing items, only adding them.
The thing that distinguishes between those two types is the index. The common array has an integer index, meaning you reference an item using a numeric index and the second type of array can have anything as an index, including complex objects and elements. More on this below.
- Common Array: index starts from zero, meaning the first item in the array will have index of 0, the second item will have index of 1 etc. They say an example is worth a thousand words, here is a thousand words then:
Add that code to the file "nomagic.html" that you created in the first part of the tutorial, or create such file now. Execute it, and see what happens.
var myFirstArray = new Array();
myFirstArray = "hello";
myFirstArray = "world";
myFirstArray = "how are you today?";
The first line declares and creates instance of an array.
The second line assigns the string "hello" to the first item of the array, the second line assigns another string to the second item and the next line assigns another string to the third item of the array.
Finally, the last line shows an alert dialog with the array items Joined together: the "join" method works on array and returns all the items joined into a single string, with the given string as the separator. When a blank space is the separator the result you'll see is "hello world how are you today?"
To count how many items an array contains, we can use the "length" property. Using the above, myFirstarray.length will return 3, because the array contains three items.
To create an array out of a string (reverse action of join) use the "split" method of the string object. Thousand words:
What happened here? I can bet you expected to get an array with three items, right?
var myString = "hello world how are you today?";
var mySecondArray = myString.split(" ");
alert("second array has " + mySecondArray.length + " items, which are:\n" + mySecondArray.join("\n"));
Well, the string "hello world how are you today?" contains five blank spaces. When used as the separator it means we have six items (words) that are separated, and the "split" method returns exactly those items. Each word in the sentence become an item in the array.
How can I get specific a item from an array? The same way as assigning: using the index. Example:
That example contains yet another way to initialize an array and assign all its items at once by giving comma separated list of values to the array constructor.
var myThirdArray = new Array("hello", "world", "how are you today?");
alert("second item in third array is: " + myThirdArray);
No surprise there, to get the second item we need to read the item with index of 1.
Now to the step-brother.
- I like to refer to this kind of array as a Collection, to distinguish it from the ordinary array described above.
Unlike an ordinary array that only stores items, a collection can also store Keys: each Key has its own Value. This is achieved because the index can be anything, thus behaving as a key.
An example will make it more clear:
Instead of assigning the items using a numeric index, we assigned them using "name" of index. What is it good for? See the bottom of this tutorial part where the final example will make good use of this type of array.
var myFirstCollection = new Array();
myFirstCollection["first key"] = "hello";
myFirstCollection["second key"] = "world";
myFirstCollection["third"] = "how are you today?";
alert(myFirstCollection["second key"] + ", " + myFirstCollection["first key"] + ", " + myFirstCollection["third"]);
Important note: this kind of array has no "length" property, and also the "join" method won't work on it. Iterating over its items is more complicated than iterating over ordinary array items; the final example will show how this can be done.
- Loop in programming means repeating the same section of code over and over. The amount of repeats is called number of iterations.
- In order to perform such thing, we need to use variable that acts as the loop iterator and its value change in each iteration. When the value of the loop iterator is reaching the desired value the loop will stop.
- The value of a loop iterator can go up as well as it can go down: it does not matter, as long as it changes and there is the stop condition.
- The value of a loop iterator can change by more than one at each iteration.
- All programming languages allow breaking out of loop in the middle, meaning before the loop iterator has reached the desired value. For this purpose, each language has its own command.
- Common usage of loops can be printing multiply values related to each other e.g. all the days in month (loop from 1 to 31) and another very common usage of loop is iterating over array items.
Thousand words will make it crystal clear: (hopefully)
What happened here? We iterated over the numbers 1 to 9, and in each iteration added the current number to string variable.
var myString = "";
for (var i = 1; i <= 9; i++)
myString += i;
The code inside the loop (that adds value to the string) was executed 9 times, because the initial value was 1 and the stop condition was when the loop iterator is bigger than 9. (More accurately, the loop was running as long as the loop iterator was equal or smaller than 9)
As you see, a loop does not have to start from 0. It can start from anything you like (not ever a number!) and can end with any condition you like.
Consider this code:
This is another kind of loop, with different syntax but same logic. The loop iterator here is a variable with the name dtIterator. The initial value is the current date, and in every loop iteration we're adding one day to the loop iterator.
var myString = "";
var dayMS = (1000 * 60 * 60 * 24);
var dtIterator = new Date();
var curMonth = dtIterator.getMonth();
while (dtIterator.getMonth() == curMonth)
myString += dtIterator + "\n";
dtIterator = new Date(dtIterator.getTime() + dayMS);
When we reach the next month, we stop. Finally, we just show the dates from the current date to the last day of the month.
The above just demonstrates that loop can have many forms, and the important part is that loop will always have section of code repeating itself and loop iterator that decides when the loop ends.
That's it for now about loops: if you have any question or something you wish to know, just ask.
Function is block of code that can be called and executed from anywhere in the code, including from other functions.
The block of code is wrapped inside the function, and you give name to that function, then in order to execute the wrapped code just use the name of the function.
A function can get as many arguments as we like, and return one single return value, of any type. (Number, String, Date or even complex type)
Classic example is function that is getting two numbers as input (arguments) and returns the sum of those two numbers:
As expected, you'll see dialog box with the number 30: our first function has two arguments: num1 and num2, and is returning the sum of those arguments.
function MyFirstFunction(num1, num2)
return num1 + num2;
What happened here? Don't worry, it's no magic so I'll explain step by step.
function Car(strModel, strColor, nInitialMileage)
this.model = strModel;
this.color = strColor;
this.mileage = nInitialMileage;
this.Drive = function CarDrive(nMilesCount)
this.mileage += nMilesCount;
this.GetModel = function CarGetModel()
this.GetColor = function CarGetColor()
this.GetCurrentMileage = function CarGetMileage()
var myFirstCar = new Car("Volvo", "black", 1500);
var mySecondCar = new Car("Jaguar", "metallic blue", 12500);
alert("my first car is " + myFirstCar.GetModel() + " and it drove total of " + myFirstCar.GetCurrentMileage() + " miles and my second car color is " + mySecondCar.GetColor() + " and it's mileage is " + mySecondCar.GetCurrentMileage());
- We created function called Car. Like with any function, it can be called from anywhere in the code and we can give it arguments. However, this function has different purpose. It does not return anything, but rather defines a car object.
- The function has three arguments, defining several properties of the car we wish to create.
- By using the keyword this inside the function we actually make is a class and cause the value we store to become global in the instance of the class we just created.
- We have defined three properties of the car object, and four methods. The properties are the car model, color and mileage. One method is Drive: it gets amount of miles the car has driven and is updating the mileage of the car accordingly. The other three methods only return the value of the car properties, exposing them to the outside world.
- Having the class at hand, we created two instances of that class, each with its own data. myFirstCar and mySecondCar holds two separate instances of the class, each sit in its own memory block.
- We used the Drive method to change the mileage of the first car.
- Finally, showing the data from both cars to prove something happened there.
As a bonus for those reading so far down the page, here is code that combines all the three parts of ALF to do something cool. Just copy into NoMagic.html and execute!
We combined arrays, loops and functions to create something that might have actual use one day: counting how many times each character appears in a given string.
var arrFuncReturnValue = new Array();
for (var i = 0; i < someString.length; i++)
var curChar = someString.substr(i, 1);
if (typeof arrFuncReturnValue[curChar] == "undefined")
arrFuncReturnValue[curChar] = 0;
var myArray = MyFirstCoolFunction("hello world, how are you today? Wonder what is going to happen...");
var sMessage = "";
for (var character in myArray)
sMessage += "The character " + character + " appeared in the string " + myArray[character] + " times.\n";
Coming next: Interacting with the user, if..then tutorial and maybe some more details about stuff we've already learned.
If you have any comments or questions, don't be shy! Post comment and say it.