There Is No Magic: JavaScript Tutorial, Part II
by
on November 29th, 2008 at 05:32 PM (796 Views)
Getting Technical With JavaScript
In this part we'll discuss ALF: Arrays, Loops and Functions, elements that are the heart of any programming language.
>>First part of tutorial
I wish to thank Don for making this tutorial use the best language possible - I could not achieve this without you, Don!
Arrays
First, a quick reminder for those who forgot:JavaScript has two types of arrays. One is very common and shared by nearly all programming languages, and the second is less known and less used.
- 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.In JavaScript it's possible to reference array items that "does not exist", for example with the first array example myFirstArray[5] will give no exception, it will just give in return "undefined" value - so be careful.
- 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.Code:<script type="text/javascript"> var myFirstArray = new Array(); myFirstArray[0] = "hello"; myFirstArray[1] = "world"; myFirstArray[2] = "how are you today?"; alert(myFirstArray.join(" ")); </script>
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?Code:<script type="text/javascript"> 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")); </script>
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.Code:<script type="text/javascript"> var myThirdArray = new Array("hello", "world", "how are you today?"); alert("second item in third array is: " + myThirdArray[1]); </script>
No surprise there, to get the second item we need to read the item with index of 1.
Those three thousand words hopefully made you familiar (and more comfortable?) with the JavaScript Array, classic type. 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.Code:<script type="text/javascript"> 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"]); </script>
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.
Loops
Quick reminder:Now that we have this clear, it's time to see how JavaScript implements loops.
- 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. 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)Code:<script type="text/javascript"> var myString = ""; for (var i = 1; i <= 9; i++) { myString += i; } alert(myString); </script>
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. 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.Code:<script type="text/javascript"> 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); } alert(myString); </script>
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.
Functions
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)
In JavaScript, function also act as class: it can wrap its own properties and methods. This is not commonly known though.
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.Code:<script type="text/javascript"> function MyFirstFunction(num1, num2) { return num1 + num2; } alert(MyFirstFunction(10, 20)); </script>
Now I'm going to introduce the other side: using functions as classes in JavaScript. Here you go:
What happened here? Don't worry, it's no magic so I'll explain step by step.Code:<script type="text/javascript"> 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() { return this.model; } this.GetColor = function CarGetColor() { return this.color; } this.GetCurrentMileage = function CarGetMileage() { return this.mileage; } } var myFirstCar = new Car("Volvo", "black", 1500); var mySecondCar = new Car("Jaguar", "metallic blue", 12500); myFirstCar.Drive(500); 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()); </script>That's it... you're now familiar with functions in JavaScript. Feel free to ask any question you like about it, I know you have questions. If you don't have any question it means you didn't read hard enough!
- 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.
- JavaScript is pretty special in the fact it allows "function inside function": this is very powerful approach, using it in order to define class methods inside the function defining the class itself is one small example.
- 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.Code:<script type="text/javascript"> function MyFirstCoolFunction(someString) { 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; } arrFuncReturnValue[curChar]++; } return arrFuncReturnValue; } 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"; } alert(sMessage); </script>
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.
Happy Programming!











Email Blog Entry