There Is No Magic: JavaScript Tutorial

Finally I've found the time to do something I planned to do
for long long time: writing tutorial for JavaScript, based on
my personal experience with JavaScript.

Keep in mind that my tutorial is not official and there
might be better ways to do some of the things. If you happen
to notice such thing then please say something so that I can
both learn and improve this tutorial.

There will be several parts, I will post each part as reply in this
thread and keep updated index here in the first post.

Here we go then!

Introduction to JavaScript

What? Why? How?

What is it?JavaScript is client sidescripting language.
This one sentence contains three phrases that need further explanation:

Client side: this means code that is under the responsibility of the browser (to differ from server side language such as PHP which is under the responsibility of the server)

Client side code is under the responsibility of the browser and this means the code is executed on the client machine (the computer of the user visiting the website, to differ from server side code that is executed on the server machine) and it runs as part of the browser process.

Client side has another important meaning: since it's executed by the browser itself, it becomes browser dependent. What does it mean? It means the same code might work on one browser and fail on other browser. (Sounds familiar?)

Scripting: the scope of this is much bigger than this article but I'll try to describe it in short.

Scripting language code is not compiled before it's executed, to differ from programming languages like C++ or Pascal or even .NET code.
Scripting language has no .exe or .dll associated file, it consists of pure text file that is the whole code.

Whenever scripting language code needs to execute, the RTE (Run Time Engine) loads the whole code into memory, compiles it "on the fly" and executes the commands in that code.
For server side scripting languages like classic ASP or PHP, the RTE is part of the server itself while in client side code, the RTE is part of the browser.
Being free of pre-compiling, scripting language does not have variable types. It simply does not need them, because the compiler does not need to allocate memory in advance for the code. It's all going to run on the memory "heap" anyway.
With no variable types available, it's also not required to declare any variables in scripting language. Many see this as blessing (less code you know) but I see this as huge curse. (I'll elaborate in the next parts of the tutorial)
Big advantage of scripting language is the ability to easily write code that write itself. It enables the programmer to do wonderful things, that are not possible in full scale programming languages.
(More about it in the next parts - be tuned)

JavaScript

What is the meaning of the language name?
It consist of two words:

Java: Yes indeed, that's the famous programming language created by Sun corporation in the beginning of the 90's.
How is it related? Syntax. The syntax of JavaScript is much alike to the syntax of Java.
Apart of syntax, JavaScript is very far from being like Java: it does not have "class" files. It's not object oriented. JavaScript is FOP: Function Oriented Programming.

Script: because JavaScript is Scripting Language with all the meanings explained above.

This pretty much explains the name.

Why JavaScript?
For various reasons:

Being client side, it runs directly on the browser thus not bound to any server.

This is the only way to deal with client events, like mouse click or key press, in real time.

Client side form validation is essential part of any respectable website. The user will prefer to know of mistakes before the data is actually submitted to the server.

Cool things like image rollover are possible only with client side code.

Cool things like "live clock", simple games.

Just in case you need to mess with elements on the page during run time. For example, replacing the URL of all the links on the page in one go.

How do I start?
Under Windows OS click Start --> Run --> type "notepad" in the textbox and click OK.
For non Windows OS just open your favorite text editor.
Copy and paste the following code into the text editor:

Code:

<html>
<head>
<title>The Magic Of JavaScript</title>
<script type="text/javascript">
alert("hello world");
</script>
</head>
<body>
This page will eventually contain some nice things that can be done with JavaScript.
</body>
</html>

Save the file under the name "nomagic.html" in your desktop.
Double click the file to launch your default browser and execute it.
If you have IE7 you'll have to click the yellow bar that appear on top of the contents and choose "Allow Blocked Content".
You should see JavaScript alert box with the message "hello world".

Congratulations! You've just wrote custom JavaScript code that is fully under your control.
Keep tuned to this article to learn the real stuff.
Coming next: Going Technical, Difference between JavaScript and VBScript and answer to questions.

If you have any comments or questions, don't be shy! Post comment and say it.

JavaScript Tutorial part II

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!

Arrays
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.

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.

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.

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?

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.

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.

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.

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.

Loops
Quick reminder:

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.

Now that we have this clear, it's time to see how JavaScript implements loops.
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)

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.

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.
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:

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.

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!

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!